在数据库表中搜索列,并将值添加到datagridview

时间:2015-06-02 08:41:30

标签: database vb.net datagridview

我想搜索item = 'apple'的值,然后将整个列添加到VB.net表单应用程序中的DataGridView。我使用以下代码行来完成我的任务,但我得到的输出是一个空白数据单元。

Dim table As DataTable = myTable.Tables("fruits")

    Dim expression, item As String

    expression = "item = 'apple'"
    Dim foundRows() As DataRow

    foundRows = table.Select(expression)

    Dim dt As New DataTable

    dt.Columns.Add("ID")
    dt.Columns.Add("item")
    dt.Columns.Add("price")

    Dim row1 As DataRow = dt.NewRow

    For Each row As DataRow In foundRows
        row1.Item("ID") = row(0)
        row1.Item("item") = row(1)
        row1.Item("price") = row(2)

    Next

    dt.Rows.Add(row1)

    DataGridView1.DataSource = dt

End Sub

2 个答案:

答案 0 :(得分:0)

您声明要添加一行(row1)并循环遍历foundRows并指定相同的var(row1),然后只将其添加到DG一次,这将导致仅添加最后找到的项目。

将代码从“Dim row1 As DataRow = dt.NewRow”更改为:

    For Each row As DataRow In foundRows
        Dim row1 As DataRow = dt.NewRow

        row1.Item("ID") = row(0)
        row1.Item("item") = row(1)
        row1.Item("price") = row(2)

        dt.Rows.Add(row1)
    Next

我不确定这是否是唯一的原因,但试一试:)

答案 1 :(得分:0)

将代码更改为此...您应按顺序添加列以按预期添加行

Dim table As DataTable = myTable.Tables("fruits")

Dim expression As String

expression = "item = 'apple'"
Dim foundRows() As DataRow

foundRows = table.Select(expression)

Dim col, col1, col2 As New DataGridViewTextBoxColumn

col.HeaderText = "ID"
col1.HeaderText = "Item"
col2.HeaderText = "Price"

DataGridView1.Columns.Add(col)
DataGridView1.Columns.Add(col1)
DataGridView1.Columns.Add(col2)

    For Each row As DataRow In foundRows
        DataGridView1.Rows.Add(row(0), row(1), row(2))
    Next