How to use checkbox in the datagridview in C # winfrom GridViewDataGridCheckBox
Method 1:
Private void dgv_zy_CellContentClick (object sender, DataGridViewCellEventArgs e)
{
Int count = Convert. ToInt16 (dgv_zy.Rows.Count.ToString ());
For (int I = 0; I <count; I ++)
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell) dgv_zy.Rows [I]. Cells ["cb_check"];
Boolean flag = Convert. ToBoolean (checkCell. Value );
If (flag = true) // find the selected data row
{
CheckCell. Value = false;
}
Else
Continue;
}
}
}
Obtain selected data
Int count = Convert. ToInt32 (dgv_zy.Rows.Count.ToString ());
For (int I = 0; I <count; I ++)
{
// If the dview is editable, submit the data. Otherwise, the row in the editing status cannot be obtained.
Dgv_zy.EndEdit ();
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell) dgv_zy.Rows [I]. Cells ["cb_check"];
Boolean flag = Convert. ToBoolean (checkCell. Value );
If (flag = true) // find the selected data row
{
// Obtain data items from the DATAGRIDVIEW
String z_zcode = dgv_zy.Rows [I]. Cells [0]. Value. ToString (). Trim ();
}
}
Method 2:
If you want to embed the checkbox column (DataGridViewCheckBoxCell) in the winform data control datagridview ),
During program execution, events like the selectedindexchanged event of the pure checkbox control may be required to capture changes in its state.
I think the better way is to use the cellcontentclick event of the datagridview control, for example:
If the embedded DataGridViewCheckBoxCell column is in the first column, you can determine the status and add processing events as follows:
Private void maid (object sender, maid e)
{
If (e. ColumnIndex = 0 & e. RowIndex! =-1)
{
// Obtain the control value
MessageBox. Show (this. maid [e. RowIndex]. Cells [0]. EditedFormattedValue. ToString ());
// Or other event handlers
}
}
Note that executing this event is the cellcontentclick event that needs to be blocked for other datagridview cells, that is, the columns except the DataGridViewCheckBoxCell
ReadOnly = True for all other columns;
You must use the EditedFormattedValue attribute to obtain the checkbox column value in the dview. this attribute obtains the value and
The value returned by FormattedValue is usually the value before editing, and when it is clicked repeatedly, an error often occurs (you cannot determine whether it is the value before editing or after editing: Main
The cause is the focus problem. you need to move the focus first so that the datagridview can retrieve the changed data in the zone. Therefore, you need to remove the data before obtaining the data.
Focus in the datagridview !!!), Therefore, you must use EditedFormattedValue to obtain the attribute value.