Vb.Net:如何执行SQL查询inisde datagrid?

时间:2013-05-02 10:23:38

标签: vb.net

我使用下面的代码加载了一个csv文件

Dim fi
Dim conn
Dim adapter1 As New OleDbDataAdapter
Dim ds As New DataSet

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    fi = New FileInfo("C:\path\Book1.csv")
    conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName)
    conn.Open()
    adapter1.SelectCommand = New OleDbCommand("SELECT * FROM " & fi.Name, conn)
    adapter1.Fill(ds, "DATA")
    DataGridView1.DataSource = ds.Tables(0).DefaultView
End Sub

现在,我想在gridview中执行诸如创建,选择,更新等SQL查询。例如,我想创建一个新列“test”并使用“a”和“b”列中的值填充该列。但我得到错误。你能否修改一下代码?

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Try
        DataGridView2.Columns.Add("test", "test")
        adapter1.SelectCommand = New OleDbCommand("Update Datagridview1 SET test = a + b", conn)
        Dim dsA As New DataSet
        adapter1.Fill(dsA, "DATA")
        DataGridView2.DataSource = dsA.Tables(0).DefaultView
    Catch exp As Exception
        MsgBox("Error : " & exp.Message)
    End Try
End Sub

1 个答案:

答案 0 :(得分:1)

我现在无法测试此代码,但通常您更改链接到DataGridView的DataTable的架构以反映新列,并且在您的特定情况下设置新创建的列的Expression属性

Dim dv As DataView = CType(DataGridView2.DataSource, DataView)
Dim dc = dv.Table.Columns.Add("test", System.Type.GetType("System.String"))
dc.Expression = "[A] + [B]"

这在很大程度上取决于A列和B列的数据类型。这里我认为它们都是字符串