我该怎么解决这个问题?
我正在做一个简单的数据库项目,我有一个搜索字段,我编写了以下代码,用于在DataGridView中搜索和显示数据,但是 Null Reference Exception一直显示,因为我没有任何内容初始化表,但如果我不这样做,我会在初始化之前使用警告。
问题是:如何正确初始化表格。
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Dim searchText As String = txtSearch.Text
Dim matchText As String = ""
Dim rowMatch As Boolean = False
Dim foundRows As DataTable = Nothing 'this initializig causes the problem of null exception,But how can i Initialize it then?????
For Each rw As DataRow In dataSet.Tables(0).Rows
Dim cl As String = rw.Item(1).ToString ' this cell is FirstName Cell
If searchText.Length > cl.ToString.Length Then
matchText = cl.ToString
Else
matchText = cl.ToString.Substring(0, searchText.Length)
End If
'bellow it adds the Found Row (rw) to the table
If (searchText.Equals(matchText) And searchText <> "" And Not foundRows Is Nothing) Then foundRows.Rows.Add(rw)
Next
'to shows data if the search text field is not empty then show the found matching rows
If (searchText <> "") Then
contactView.DataSource = foundRows
Else ' else show the original tavle again
contactView.DataSource = dataSet.Tables(0)
End If
contactView.Refresh() 'refresh
End Sub
我尝试使用
Dim foundRows As DataTable = New DataTable
但它显示 ArgumentException
此行已属于另一个表
{{3}}
但是你可以看到没有任何效果,请帮助!
答案 0 :(得分:0)
是 我终于明白了
我的栏目有问题
Dim foundRows As DataTable = New DataTable("PseuContact") 'this initializig causes the problem of null exception,But how can i Initialize it then?????
foundRows.Columns.Add("ID")
foundRows.Columns.Add("First Name")
foundRows.Columns.Add("Last Name")
foundRows.Columns.Add("Phone Number")
foundRows.Columns.Add("Mobile Number")
foundRows.Columns.Add("Email Address")
在声明新表时,初始化列很重要
这是最好的