简体   繁体   中英

Make Checkbox Column Checked when Row Selected in Datagridview VB.NET

Hello Everyone Good Afternoon.

I have a question,

I have Checkbox Column in Datagridview and the Column is in 0.

How can i make the Checkbox Column Checked when a Specific Row is Selected in Datagridview? Make the checkbox column checked when a row is Selected.

Here is my code

Code connected to another Code when populating Data from Database to Datagridview

 Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
        checkBoxColumn.HeaderText = "Tag"
        checkBoxColumn.Width = 30
        checkBoxColumn.Name = "checkBoxColumn"
        DataGridView1.Columns.Insert(0, checkBoxColumn)

Code when selecting row.

 Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        If e.ColumnIndex = DataGridView1.Columns(0).Index Then
            DataGridViewCheckBoxColumn_Uncheck()
            Dim cell As DataGridViewCheckBoxCell = DataGridView1.Rows(e.RowIndex).Cells(0)
            cell.Value = cell.TrueValue
        End If
    End Sub
    Private Sub DataGridViewCheckBoxColumn_Uncheck()
        For Each row As DataGridViewRow In DataGridView1.Rows
            Dim cell As DataGridViewCheckBoxCell = row.Cells(0)
            cell.Value = cell.FalseValue
        Next
    End Sub

My code has no error but the prob. here is I really need to Select the Checkbox Column and Checked on it and when the Row Selection Changed the Last Selected is Unchecked.

I hope you get me.

TYSM for future Help

Try to change your code to :

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

            Dim cell As DataGridViewCheckBoxCell = DataGridView1.Rows(e.RowIndex).Cells(0)

            DataGridViewCheckBoxColumn_Uncheck()
            cell.Value = True

        End Sub
  Private Sub DataGridViewCheckBoxColumn_Uncheck()
        For Each row As DataGridViewRow In DataGridView1.Rows
            Dim cell As DataGridViewCheckBoxCell = row.Cells(0)
            cell.Value = False
        Next
    End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM