LuckyLuke82 LuckyLuke82 - 5 months ago 84
Vb.net Question

Datagridview - edit selected row?

I have set Datagridview .ReadOnly property to True, and then added a button column. Button column is meant for edit button when clicked, but I wish to edin only currently selected row. This is what I tried:

EDIT:

Public Class Form2

Private Sub Form2_Resize(sender As Object, e As EventArgs) Handles Me.Resize
Me.DataGridView1.Height = 0.8 * Me.Height
End Sub

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Users._USERS' table. You can move, or remove it, as needed.
Me.USERSTableAdapter.Fill(Me.Users._USERS)
Me.DataGridView1.DefaultCellStyle.Font = New Font("Arial", 7)

End Sub

Protected Overrides Sub OnLoad(e As EventArgs)
MyBase.OnLoad(e)
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).ReadOnly = True
Next
End Sub

Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick

Dim yourColumnIndex As Int32 = 3
If e.ColumnIndex = yourColumnIndex Then

If MsgBox("Do you wish to edit records?", vbQuestion + vbYesNo, "Edit records") = vbYes Then
DataGridView1.Rows(e.RowIndex).ReadOnly = False

End If
End If

End Sub

Private Sub DataGridView1_RowLeave(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
DataGridView1.Rows(e.RowIndex).ReadOnly = True
End Sub


End Class

Answer

This is working, I just changed your suggestion a little bit (DatagridView Readonly property must be set to False):

Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)
        For Each band As DataGridViewBand In DataGridView1.Columns
            band.ReadOnly = True
        Next
End Sub

Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim yourColumnIndex As Int32 = 3
If e.ColumnIndex = yourColumnIndex Then
   If MsgBox("Do you wish to edit record?", vbQuestion + vbYesNo, "Edit      record") = vbYes Then
   For Each band As DataGridViewBand In DataGridView1.Columns
       band.ReadOnly = False
   Next
   End If
End If
End Sub

Private Sub DataGridView1_RowLeave(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
    For Each band As DataGridViewBand In DataGridView1.Columns
        band.ReadOnly = True
    Next
End Sub

Thanks for all your help Lars!