2017-05-25 72 views
1

我有一個Datagridview網格有四列。當單元格被雙擊時,所選行上的數據被傳遞給四個文本框供用戶進行更改(如果有)。那麼如何將所做更改傳遞給所選行而不是將更改添加爲新行?編輯選定的Datagridview行vb.Net

P.S.該數據不是來自數據庫的

+0

網格中的數據是否存儲在DataTable中?它是數據庫中表的視圖嗎?顯示一些設置網格的「DataSource」的代碼。 – David

+0

否數據不是來自數據庫。 –

+0

叫什麼主鍵?我假設數據中有某種唯一標識符? – David

回答

1

您可以通過設置模塊級別變量來「記住」DataGridViewRow,或者可以通過查找其主鍵再次找到該行。

Public Class Form1 
    'Add to form: 
    ' DataGridView called DataGridView1 
    ' 4 Textboxes called TextBox1, TextBox2, TextBox3, and TextBox4 
    ' Button called btnEdit 
    ' Button called btnSave 

    Private mintRowWeAreEditing As Integer = -1 
    Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click 
    If DataGridView1.DataSource Is Nothing Then 
     'set initial data 
     Dim dtb As New DataTable 
     dtb.Columns.Add("Col1") 
     dtb.Columns.Add("Col2") 
     dtb.Columns.Add("Col3") 
     dtb.Columns.Add("Col4") 
     dtb.Rows.Add("R1C1", "R1C2", "R1C3", "R1C4") 
     dtb.Rows.Add("R2C1", "R2C2", "R2C3", "R2C4") 
     dtb.Rows.Add("R3C1", "R3C2", "R3C3", "R3C4") 
     dtb.Rows.Add("R4C1", "R4C2", "R4C3", "R4C4") 
     DataGridView1.DataSource = dtb 
    End If 
    'copy data from grid to textboxes 
    mintRowWeAreEditing = DataGridView1.CurrentCell.RowIndex 
    Dim drw As DataRow = DirectCast(DataGridView1.Rows(mintRowWeAreEditing).DataBoundItem, DataRowView).Row 
    TextBox1.Text = drw("Col1").ToString 
    TextBox2.Text = drw("Col2").ToString 
    TextBox3.Text = drw("Col3").ToString 
    TextBox4.Text = drw("Col4").ToString 
    End Sub 

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click 
    'copy data from textboxes to grid 
    If mintRowWeAreEditing = -1 Then Exit Sub 'haven't clicked Edit button yet 
    Dim drw As DataRow = DirectCast(DataGridView1.Rows(mintRowWeAreEditing).DataBoundItem, DataRowView).Row 
    drw("Col1") = TextBox1.Text 
    drw("Col2") = TextBox2.Text 
    drw("Col3") = TextBox3.Text 
    drw("Col4") = TextBox4.Text 
    End Sub 
End Class 
+0

你可以通過示例代碼解釋嗎? –

+0

好的,我添加了一些演示代碼。 – SSS

+0

非常感謝,工作得很好。 –

0

因此,舉例來說,你可以做你的按鈕單擊事件這樣的事情。

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click 


    Dim refNo As Integer = txtRefNo.Text  ' Change DataType and TextBox name as appropriate 
    Dim firstName as String = txtFName.Text 
    ' Repeat setting variables for each field in the row that you're updating 

    For Each dgr As DataGridViewRow in DataGridView1.Rows 
    If dgr.Item("RefNo") = refNo Then 
     dgr.Cells(0).Value = firstName 'Instead of using (0) you can use the column name 
     dgr.Cells(1).Value = newVar 
    End If 
    Next 

' Commit the changes/refresh here 

End Sub 

我沒有IDE手來測試這一點,但任何問題,讓我知道,我會看看到它。

+0

謝謝戴維。 –