- Datatable DT; (able bound to the datagridview dview)
- Datagridview dgview;
- DT. Columns. Add ("check", typeof (bool ));
- Dgview. Columns. Clear ();
- Dgview. autogeneratecolumns = false;
- Dgview. datasource = DT;
- Datagridviewcheckboxcolumn dtcheck = new datagridviewcheckboxcolumn ();
- // (Note that this is the datagridviewcheckboxcolumn instead of the datagridviewtextboxcolumn)
- Dtcheck. datapropertyname = "check ";
- Dtcheck. headertext = "";
- Dgview. Columns. Add (dtcheck );
- Dgview. Columns [0]. width = 30;
After adding the workbook, open the small arrow in the upper-right corner of the datagridview form and select the check box before "editable". Otherwise, the check box cannot be used.
If you set the columnheadersvisible attribute of the datagridview to false, there will be no column headers, which is better!
- DatatableDt = (Datatable) Dgview. datasource;
- // Usage
- Foreach (datarow row in DT. Rows)
- {
- If (row ["check"]. tostring () = "true ")
- {
- //
- }
- }
When you cannot select multiple check boxes, add the following code to the cellvaluechanged and currentcelldirtystatechanged events of the dview:
- Private void datagridview1_currentcelldirtystatechanged (Object sender, eventargs E)
- {
- Datagridview dgv = (datagridview) sender;
- If (dgv. iscurrentcelldirty)
- {
- Dgv. commitedit (maid. Commit );
- }
- }
- Private void maid (Object sender, maid E)
- {
- If (E. columnindex = 0)
- {
- Datagridview dgv = (datagridview) sender;
- Datatable dt = (datatable) dgv. datasource;
- Datagridviewcheckboxcell checkcell = (datagridviewcheckboxcell) dgv. Rows [E. rowindex]. cells [0];
- Bool value = (Boolean) checkcell. value;
- For (INT I = 0; I <DT. Rows. Count; I ++)
- {
- Datarow ROW = DT. Rows [I];
- If (I! = E. rowindex & value)
- {
- Row ["check"] = false;
- }
- }
- Dgv. invalidate ();
- }
- }