通过字典列表 VB.NET 将项目添加到 DataTable

发布于 2025-01-12 00:01:33 字数 828 浏览 0 评论 0原文

我正在尝试将字典中的值添加到 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 技术交流群。

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

发布评论

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

评论(1

念三年u 2025-01-19 00:01:33

每次单击 Button 时,都会创建一个新的 Dictionary 对象,用一对数据填充它,创建一个新的 DataTable 对象,然后传输该对象一对数据,然后显示该数据。这意味着丢弃已经显示的数据。如果您希望数据持久存在,那么您需要停止创建新对象并一直丢弃旧对象。

您最好摆脱Dictionary,因为它毫无意义。您只需要DataTable。首先创建一个 DataTable 并将其绑定到网格。然后,您只需在读取数据时将每个数据对添加到 DataTable 中,它就会自动出现在网格中,因为这就是绑定点。

Every time you click the Button, you create a new Dictionary object, populate it with one data pair, create a new DataTable 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 the DataTable. Create a single DataTable at the outset and bind that to the grid. You can then just add each data pair to the DataTable as you read it and it will automatically appear in the grid, as that's the point of binding.

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