0

我已经使用下面的代码加载了一个 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
4

1 回答 1

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 的数据类型。这里我假设它们都是字符串

于 2013-05-02T10:55:33.033 回答