简体   繁体   English

基于Datagridview列的单元格内容的复选框状态

[英]Checkbox state Based on cell content of Datagridview Column

I had this problem on how do i make the checkbox state change when the cell content in the column 1 of my datagridview? 我在datagridview的第1列中的单元格内容如何更改复选框状态时遇到此问题?

For example: 例如:

I have this datagridview with two columns, Column 1 and Column 2. 我有两个列,第1列和第2列的datagridview。

Column 1 - represents numbers/integer like 1 or 2 and Column 2 - DataGridView CheckBoxColumn 第1列-表示数字/整数,如1或2,第2列-DataGridView CheckBoxColumn

Case is: 案例是:

If the value of cell in Column 1 = 1, column 2 which is the DataGridView CheckBoxColumn, Checkbox state is "Checked" 如果第1列中的单元格的值= 1,第2列是DataGridView CheckBoxColumn,则复选框状态为“已检查”

If the value of cell in Column 1 = 2, column 2 which is the DataGridView CheckBoxColumn, Checkbox state is "UnChecked" 如果列1 = 2中的单元格的值是列2,即DataGridView CheckBoxColumn,则复选框状态为“未检查”

How do i do this in vb.net code? 我该如何在vb.net代码中执行此操作?

You need to iterate over each row of the grid, then make a comparison to set the value of the CheckBox 您需要遍历网格的每一行,然后进行比较以设置CheckBox的值

For Each row As DataGridViewRow in yourGrid.Rows
   If row.Columns("Column1").Value = 1 Then
      row.Columns("Column2").Value = True
   Else
      row.Columns("Column2").Value = False
   End If
Next

You can use this with an event on your cell: 您可以将其与单元格上的事件一起使用:

Public Class Form1

Private Sub Val_change(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellValidated
    Dim val As String = Me.DataGridView1.CurrentCell.Value
    If val = "1" Then
        DataGridView1.Rows(0).Cells(1).Value = True
    Else
        DataGridView1.Rows(0).Cells(1).Value = False
    End If
End Sud
End Class

If you use DataTable bound to the data grid view , try to add a new expression column to the data table and bind it to the checkbox column in the DataGridView. 如果您使用绑定到数据网格视图的DataTable,请尝试将新的表达式列添加到数据表并将其绑定到DataGridView中的复选框列。

the new expression column can be like below 新的表达式列可以如下所示

 Dim checkBoxColumn As DataColumn = New DataColumn
 With checkBoxColumn
     .DataType = System.Type.GetType("System.Boolean")
     .ColumnName = "CheckBoxColumn"
     .Expression = "IIF(Column1=1 ,True,False)"
 End With

 'add the new column to your dataTale
 myTable.Columns.Add(checkBoxColumn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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