在DataGridView中搜索带有输出的JSON文件的内容

发布于 2025-02-02 18:51:30 字数 3024 浏览 2 评论 0 原文

该表单具有文本字段和一个datagridView。不必在数据杂志中显示JSON文件的整个内容,以搜索JSON文件的内容并在DataGridView中显示搜索结果。
您需要在用户名标签上搜索。您需要在文本字段中开始键入名字或姓氏,然后在DataGridView中显示找到的结果。

如何在DataGridView中读取文本文件:

Imports System.IO
Imports Newtonsoft.Json

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim result = JsonConvert.DeserializeObject(Of List(Of Users))(File.ReadAllText("D:\Users.json"))
        DataGridView1.DataSource = result
    End Sub

      Public Class Users
        Public Property ID() As Integer
        Public Property UserName() As String
        Public Property Login() As String
        Public Property Title() As String
        Public Property Dep() As String
        Public Property Mail() As String
        Public Property Phone() As String
    End Class
End Class

我也知道如何进行文件搜索。仅出于某种原因显示结果 - 第一个元素找到:

Dim json As String = File.ReadAllText("D:\Users.json")
Dim objectList = JsonConvert.DeserializeObject(Of List(Of Users))(json)
Dim foundItem = objectList.Where(Function(underscore) underscore.UserName.Contains("Tom")).FirstOrDefault()

If foundItem IsNot Nothing Then
    MessageBox.Show(foundItem.UserName)
Else
    MsgBox("none")
End If

JSON文件本身的实际内容:

[
{
"id":"1",
"UserName":"Fred Smith",
"Login":"f.smith",
"Title":"engineer",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"111",
},
{
"id":"2",
"UserName":"Ben Taylor",
"Login":"b.taylor",
"Title":"programmer",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"100",
},
{
"id":"3",
"UserName":"Steve Harris",
"Login":"s.harris",
"Title":"System Administrator",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"263",
},
{
"id":"4",
"UserName":"Tom Walker",
"Login":"t.walker",
"Title":"engineer",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"263",
},
{
"id":"5",
"UserName":"Tom Davis",
"Login":"t.davis",
"Title":"engineer",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"200",
},
{
"id":"6",
"UserName":"Ben Walker",
"Login":"b.walker",
"Title":"System Administrator",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"167",
},
]

The Form has a text field and a DataGridView. It is necessary, without displaying the entire contents of the JSON file in the DataGridView, to search the content of the JSON file and display the search result in the DataGridView.
You need to search by the UserName tag. You need to start typing either the first or last name in the text field and in the DataGridView display the result of the found.

How to read text file in DataGridView I know:

Imports System.IO
Imports Newtonsoft.Json

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim result = JsonConvert.DeserializeObject(Of List(Of Users))(File.ReadAllText("D:\Users.json"))
        DataGridView1.DataSource = result
    End Sub

      Public Class Users
        Public Property ID() As Integer
        Public Property UserName() As String
        Public Property Login() As String
        Public Property Title() As String
        Public Property Dep() As String
        Public Property Mail() As String
        Public Property Phone() As String
    End Class
End Class

I also know how to do a file search. Only for some reason the result displays - the first element found:

Dim json As String = File.ReadAllText("D:\Users.json")
Dim objectList = JsonConvert.DeserializeObject(Of List(Of Users))(json)
Dim foundItem = objectList.Where(Function(underscore) underscore.UserName.Contains("Tom")).FirstOrDefault()

If foundItem IsNot Nothing Then
    MessageBox.Show(foundItem.UserName)
Else
    MsgBox("none")
End If

And the actual contents of the json file itself:

[
{
"id":"1",
"UserName":"Fred Smith",
"Login":"f.smith",
"Title":"engineer",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"111",
},
{
"id":"2",
"UserName":"Ben Taylor",
"Login":"b.taylor",
"Title":"programmer",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"100",
},
{
"id":"3",
"UserName":"Steve Harris",
"Login":"s.harris",
"Title":"System Administrator",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"263",
},
{
"id":"4",
"UserName":"Tom Walker",
"Login":"t.walker",
"Title":"engineer",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"263",
},
{
"id":"5",
"UserName":"Tom Davis",
"Login":"t.davis",
"Title":"engineer",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"200",
},
{
"id":"6",
"UserName":"Ben Walker",
"Login":"b.walker",
"Title":"System Administrator",
"Dep":"IT infrastcomcture",
"Mail":"[email protected]",
"Phone":"167",
},
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

歌入人心 2025-02-09 18:51:30

需要注意的几件事:

  • 此处介绍的JSON代表了所有具有相同属性的对象。它可以被视为 Records Rows 的数组。
  • 您需要对此JSON进行挑选,在DataGridView中介绍结果,并允许用户过滤并可能对数据进行排序。

您目前可以将此JSON划分为简单收集的类对象,这很好。如果您想过滤和排序此集合,它可能会变得更加复杂,因为一个简单的 list< t> 本身不支持它。绑定清单也不是。
您应该实现 ibindinglistview 处理对象列表,并且很可能还很可能还处理基类中的接口(您的当前用户类)。
或者使用ORM / Mini-orm。

已经建立了一种已经实现所有这些功能的已经建立的(和测试)类型noreferrer“> datatable class。
如前所述,您的JSON实际上是一个表( Records 的数组),因此将其列为数据表非常简单。只是:

Dim dt = JsonConvert.DeserializeObject(Of DataTable)(json) 

数据级类已经允许过滤,设置其属性和排序,设置其 DefaultView.Sort 属性。

尽管如此,我建议使用介体在数据词和UI之间。
该工具非常有用,因为它提供了过滤和分类数据源的常用方法,但只要数据源实际上具有这些功能。
使用BindingSource,无论数据源是什么。
它还生成了一些有用的事件,如
currentchanged 活动等等。
ListChanged 事件还提供了指定更改类型的参数。

使用BindingSource,以序列化回JSON,如果数据发生了变化:

[BindingSource].EndEdit()
Dim json = JsonConvert.SerializeObject([BindingSource].DataSource, Formatting.Indented)

在示例代码中,使用这些对象(请参阅视觉示例):

  • usersSource :bindingsource对象
  • tboxfilteruser < /code>:文本框控件,使用用户名 property
  • tboxFilterTitle :一个文本框控件,使用 title> title> title property过滤
  • 数据代码> btnremovefilter :用于删除当前过滤器的按钮控件
  • dgv :dataGridView控件

Public Class SomeForm

    Private UsersSource As New BindingSource()
    ' Current filters
    Private UserNameFilter As String = "UserName LIKE '%%'"
    Private UserTitleFilter As String = "Title LIKE '%%'"

    Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)

        Dim json = File.ReadAllText("D:\Users.json")
        Dim dt = JsonConvert.DeserializeObject(Of DataTable)(json)
        dt.AcceptChanges()
        UsersSource.DataSource = dt
        dgv.DataSource = UsersSource
    End Sub

    Private Sub tBoxFilterUser_TextChanged(sender As Object, e As EventArgs) Handles tBoxFilterUser.TextChanged
        Dim tbox = DirectCast(sender, TextBox)
        UserNameFilter = $"UserName LIKE '%{tbox.Text}%'"
        UsersSource.Filter = $"{UserNameFilter} AND {UserTitleFilter}"
    End Sub

    Private Sub tBoxFilterTitle_TextChanged(sender As Object, e As EventArgs) Handles tBoxFilterTitle.TextChanged
        Dim tbox = DirectCast(sender, TextBox)
        UserTitleFilter = $"Title LIKE '%{tbox.Text}%'"
        UsersSource.Filter = $"{UserNameFilter} AND {UserTitleFilter}"
    End Sub

    Private Sub btnRemoveFilter_Click(sender As Object, e As EventArgs) Handles btnRemoveFilter.Click
        tBoxFilterUser.Clear()
        tBoxFilterTitle.Clear()
        UsersSource.RemoveFilter()
    End Sub
End Class

这是其工作方式:

“

A few things to note:

  • The JSON presented here represent an array of objects which all have the same properties. It can be considered an array of records or Rows.
  • You need to deserialize this JSON, present the result in a DataGridView and allow the user to filter and probably sort the data.

You're currently deserializing this JSON to simple collection a class objects, which is perfectly fine. It may become a little more complex if you want to filter and sort this collection, since a simple List<T> doesn't support it by itself. Nor does a BindingList.
You should implement the IBindingListView interface in a class that handles the List of objects and most probably also the INotifyPropertyChanged interface in the base class (your current Users class).
Or use an ORM / Mini-ORM instead.

There's an already built (and tested) Type that already implements all these features, the DataTable class.
Since, as mentioned, your JSON IS actually a Table (an array of records), deserializing it to a DataTable is quite straightforward. It's just:

Dim dt = JsonConvert.DeserializeObject(Of DataTable)(json) 

The DataTable class already allows filtering, setting its DefaultView.RowFilter property and sorting, setting its DefaultView.Sort property.

Nonetheless, I suggest to use a BindingSource as mediator between the DataTable and the UI.
This tool is quite useful, since it provides common methods to filter and sort a source of data, provided that the source of data actually has these capabilities.
Using a BindingSource, you always use the same methods, no matter what the source of data is.
It also generates some useful events, as the ListChanged, AddingNew, CurrentChanged events and more.
The ListChanged event also provides arguments that specify the type of change.

With a BindingSource, to serialize back to JSON, if the the data has changed:

[BindingSource].EndEdit()
Dim json = JsonConvert.SerializeObject([BindingSource].DataSource, Formatting.Indented)

In the sample code, these objects are used (see the visual example):

  • UsersSource: the BindingSource object
  • tBoxFilterUser: a TextBox Control, filters the data using the UserName Property
  • tBoxFilterTitle: a TextBox Control, filters the data using the Title Property
  • btnRemoveFilter: a Button Control used to remove the current filters
  • dgv: a DataGridView Control

Public Class SomeForm

    Private UsersSource As New BindingSource()
    ' Current filters
    Private UserNameFilter As String = "UserName LIKE '%%'"
    Private UserTitleFilter As String = "Title LIKE '%%'"

    Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)

        Dim json = File.ReadAllText("D:\Users.json")
        Dim dt = JsonConvert.DeserializeObject(Of DataTable)(json)
        dt.AcceptChanges()
        UsersSource.DataSource = dt
        dgv.DataSource = UsersSource
    End Sub

    Private Sub tBoxFilterUser_TextChanged(sender As Object, e As EventArgs) Handles tBoxFilterUser.TextChanged
        Dim tbox = DirectCast(sender, TextBox)
        UserNameFilter = 
quot;UserName LIKE '%{tbox.Text}%'"
        UsersSource.Filter = 
quot;{UserNameFilter} AND {UserTitleFilter}"
    End Sub

    Private Sub tBoxFilterTitle_TextChanged(sender As Object, e As EventArgs) Handles tBoxFilterTitle.TextChanged
        Dim tbox = DirectCast(sender, TextBox)
        UserTitleFilter = 
quot;Title LIKE '%{tbox.Text}%'"
        UsersSource.Filter = 
quot;{UserNameFilter} AND {UserTitleFilter}"
    End Sub

    Private Sub btnRemoveFilter_Click(sender As Object, e As EventArgs) Handles btnRemoveFilter.Click
        tBoxFilterUser.Clear()
        tBoxFilterTitle.Clear()
        UsersSource.RemoveFilter()
    End Sub
End Class

This is how it works:

JSON to DataTable

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文