通过字典列表 VB.NET 将项目添加到 DataTable
我正在尝试将字典中的值添加到 DataTable 中。字典的键值对是从表单中填充的。但 DataTable 仅从表单中获取最后插入的值。为什么会这样呢?
Public Class dictionary
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dictionary_ As New Dictionary(Of String, String)
Dim value_ As String
Dim key_ As String
value_ = TextBox1.Text
key_ = TextBox2.Text
dictionary_.Add(value_, key_)
Add_Data(dictionary_)
End Sub
Private Sub Add_Data(ByVal dic_ As Dictionary(Of String, String))
Dim dt As New DataTable()
dt.Columns.Add("KEY")
dt.Columns.Add("VALUE")
For Each item As KeyValuePair(Of String, String) In dic_
dt.Rows.Add(item.Key, item.Value)
Next
dataGrid_.DataSource = dt
End Sub
End Class
I am trying to add values to DataTable from dictionary. The key value pair for the dictionary is filled from the form. But the DataTable is only taking the last inserted value from the form. Why is it so?
Public Class dictionary
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dictionary_ As New Dictionary(Of String, String)
Dim value_ As String
Dim key_ As String
value_ = TextBox1.Text
key_ = TextBox2.Text
dictionary_.Add(value_, key_)
Add_Data(dictionary_)
End Sub
Private Sub Add_Data(ByVal dic_ As Dictionary(Of String, String))
Dim dt As New DataTable()
dt.Columns.Add("KEY")
dt.Columns.Add("VALUE")
For Each item As KeyValuePair(Of String, String) In dic_
dt.Rows.Add(item.Key, item.Value)
Next
dataGrid_.DataSource = dt
End Sub
End Class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每次单击
Button
时,都会创建一个新的Dictionary
对象,用一对数据填充它,创建一个新的DataTable
对象,然后传输该对象一对数据,然后显示该数据。这意味着丢弃已经显示的数据。如果您希望数据持久存在,那么您需要停止创建新对象并一直丢弃旧对象。您最好摆脱
Dictionary
,因为它毫无意义。您只需要DataTable
。首先创建一个DataTable
并将其绑定到网格。然后,您只需在读取数据时将每个数据对添加到 DataTable 中,它就会自动出现在网格中,因为这就是绑定点。Every time you click the
Button
, you create a newDictionary
object, populate it with one data pair, create a newDataTable
object, transfer that one data pair and then display that data. That means discarding the data already displayed. If you want the data to persist then you need to stop creating new objects and discarding the old ones all the time.You may as well get rid of the
Dictionary
as it is pointless. You only need theDataTable
. Create a singleDataTable
at the outset and bind that to the grid. You can then just add each data pair to theDataTable
as you read it and it will automatically appear in the grid, as that's the point of binding.