用户单击DataGridViewComboBoxColumn时刷新DataGridViewTextBoxColumn

时间:2016-01-06 07:58:05

标签: .net vb.net winforms datagrid datagridcomboboxcolumn

假设我有以下 DataGrid

DataGrid

第一列是 DataGridViewComboBoxColumn 。用户单击 ComboBox 中的一个产品时的示例,我希望列价格的列 DataGridViewTextBoxColumn 被刷新或更新由ComboBox的选择更改。

下面是我的普通TextBox代码。如何刷新DataGridViewTextBoxColumn?

Private Sub refresh_grid(ByVal productOrder As String)
        Dim mysql As String = "SELECT FLD_PRODUCT_PRICE FROM TBL_PRODUCTS "
        Dim mydatatable As New DataTable
        Dim myreader As New OleDb.OleDbDataAdapter(mysql, myconnection)
        myreader.Fill(mydatatable)

        Price = mydatatable.Rows(0).Item("FLD_PRODUCT_PRICE")

    End Sub

1 个答案:

答案 0 :(得分:0)

您可以将DataGridView.CellValueChanged用于此

'This is your function for getting a Price based on product
'Use your returned type of Price value
Private Function GetPrice(selectedProduct As String) As Decimal 
    Dim mysql As String = "SELECT FLD_PRODUCT_PRICE FROM TBL_PRODUCTS "
    Dim mydatatable As New DataTable
    Dim myreader As New OleDb.OleDbDataAdapter(mysql, myconnection)
    myreader.Fill(mydatatable)

    Return mydatatable.Rows(0).Item("FLD_PRODUCT_PRICE")
End Function

Private Sub DataGridView_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs)
    if e.RowIndex < 0 Then Exit Sub 'Exit if current row is Header row
    Dim dgv As DataGridView = DirectCast(sender, DataGridView)
    Dim comboBoxColumnIndex As Integer = 0
    Dim textboxColumnIndex As Integer = 1
    if e.ColumnIndex = comboBoxColumnIndex Then
        'Get price and update "Price" column
        Dim product As String = dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString()
        Dim price As Decimal = Me.GetPrice(product)
        dgv.Rows(e.RowIndex).Cells(textboxColumnIndex).Value = price
    End If

End Sub

或者您可以使用DataGridView.CellEndEdit eventhandler,只有在用户编辑了值时才会引发该事件处理程序 您可以在CellEndEdit eventhandler中使用相同的代码,因为DataGridViewCellEventArgs类型也包含RowIndexColumnIndex条款