2016-01-06 63 views
0

假設我有數據網格下面刷新DataGridViewTextBoxColumn當用戶點擊DataGridViewComboBoxColumn

DataGrid

第一列是DataGridViewComboBoxColumn。當用戶單擊組合框中的一個產品時,我想要列DataGridViewTextBoxColumn這是列價格要刷新或更新由組合框的選擇更改觸發。

下面是我的普通文本框的代碼。我如何刷新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 
+0

'DataGridView.CellValueChanged Event' [從MSDN(https://msdn.microsoft.com/en-us/library/system .windows.forms.datagridview.cellvaluechanged(v = vs.110).aspx) – Fabio

回答

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事件處理程序,當值編輯BU用戶將只能提高。
您可以使用相同的代碼裏面CellEndEdit事件處理程序,因爲DataGridViewCellEventArgs類型包含RowIndexColumnIndex proerties太

+0

我嘗試過,但仍然不會更新價格列,當我更改選定的產品? –

+1

將我的代碼看作「僞代碼」,它非常接近'vb.net'。檢查事件處理程序是否連接到事件。將「Handle」添加到行Private Sub DataGridView_CellValueChanged(sender As Object,e As DataGridViewCellEventArgs)處理YourDataGridView.CellValueChanged'。如果不工作,那麼調試一行代碼並檢查事件是否正確提出並且代碼被執行 – Fabio

+0

好吧,我的壞。我錯過了。所以我試過了,無論我在列產品上選擇哪種產品,它都會顯示與數據庫中第一行數據相同的價格。你能解釋爲什麼嗎? –

相關問題