使用数据绑定控件

时间:2015-08-07 10:02:47

标签: mysql vb.net datagridview

我有一个带有两个datagridview的表单,它从mysql数据库中获取项目。

我的目标是点击第一个DGV的项目并将其插入第二个,然后(按一个按钮)更新数据库中的表格。

问题是我无法添加一行(我得到异常:无法在数据绑定控件时以编程方式将行添加到DataGridView中的行集),如果我以编程方式填充最后一行(用于手动插入的行) )没有获得价值。

但如果我手动填写最后一行并按下"更新按钮"数据库变得更新。

这是" CellContentClick"

的代码
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    Dim DvgRow% = e.RowIndex
    Dim DvgCol% = e.ColumnIndex
    Dim SelCell$ = Me.DataGridView1.Item(DvgCol, DvgRow).Value.ToString.Trim()
    Dim IntColSel$ = Me.DataGridView1.Columns(DvgCol).HeaderText

    Dim Dgv2Rows% = Me.DataGridView2.RowCount

    If IntColSel.ToUpper = "REGION" Then
        'Here I get the value in the last row but is ignored being updated
        Me.DataGridView2.Item(0, Me.DataGridView2.RowCount - 1).Value = SelCell 
        'Here I get exception
        Me.DataGridView2.Rows.Add() 
    End If
End Sub

这是填补第二个DGV的代码:

Private Sub GetInDGV2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click

    With DataGridView2
        .DataSource = Nothing
        .Rows.Clear()
        .Columns.Clear()
    End With
    cnString = "datasource=" + Server_Name + ";username= " + UserDB + _
        ";password=" + Password + ";database=" + Database_Name + ""
    sqlQRY2 = "Select Region from regions"
    conn = New MySqlConnection(cnString)
    Try
        conn.Open()
        da2 = New MySqlDataAdapter(sqlQRY2, conn)
        Dim cb2 As MySqlCommandBuilder = New MySqlCommandBuilder(da2)
        da2.Fill(ds2, "regions")
        DataGridView2.DataSource = ds2
        DataGridView2.DataMember = "regions"
    Catch ex As Common.DbException
        MsgBox(ex.ToString)
    Finally
        conn.Close()
    End Try
End Sub

我看到了this question aswered,但我无法从C中进行翻译测试。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

由于DataGridview2与DataTable2绑定,因此无法直接修改单元格。您必须通过添加新的DataRow来更新DataTable2。添加后,DataGRidView2将自动刷新。

要获取填充新DataRow所需的RowValues,您可以访问DataTable1 DataRow。获取基础DataTable1的DataRow,对应于dataGridView1的当前行:

Dim selectedrow As DataRow = DirectCast(DataGridView1.CurrentRow.DataBoundItem, DataRowView).Row ;

然后在DataTable2中创建一个新的DataRow,其值来自slectedrow。

Dim dataTable2 As DataTable = ds2("Regions") 
Dim newrow As DataRow = dataTable2.NewRow() 
For i As Integer = 0 To selectedrow.Count - 1
  newrow(i) = selectedrow(i)
Next
dataTable2.Rows.Add(newrow)