該表單有一個文本欄位和一個資料網格視圖。需要在DataGridView中不顯示json檔案全部內容的情況下,搜索json檔案,并在DataGridView中顯示搜索結果。需要通過UserName標簽進行搜索。您需要開始在文本欄位中輸入名字或姓氏,并在 datagridview 中顯示找到的結果
我知道如何在 dataGridView 中讀取文本檔案:
Imports System.IO
Imports Newtonsoft.Json
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
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",
},
]
uj5u.com熱心網友回復:
需要注意的幾點:
- 這里呈現的 JSON 表示一個物件陣列,它們都具有相同的屬性。它可以被認為是一組記錄或行。
- 您需要反序列化此 JSON,在 DataGridView 中顯示結果,并允許用戶過濾并可能對資料進行排序。
您目前正在將此 JSON 反序列化為簡單的類物件集合,這非常好。如果你想過濾和排序這個集合,它可能會變得有點復雜,因為一個簡單List<T>的不支持它本身。BindingList 也沒有。
您應該在處理物件串列的類中實作
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/486448.html
