C # Summary (iii) DataGridView Add a Select all column

Source: Internet
Author: User

A recent WinForm project that encountered the first column of the DataGridView Control adds a feature that is all-in-one, usually in two ways: 1. Add Datagridviewcheckboxcolumn to the control, but you need to provide a select-All option, 2. Add a CheckBox control to the DataGridView combination to achieve a select-all option. However, the feeling that both implementations are not very good. Online search data, found a foreigner's implementation method, relatively simple and general. The bottom connection of the demo code is given.

His way of realization is: Datagridviewcheckboxcolumn's parent class DataGridViewColumnHeaderCell has a Headercell attribute in it, Look at the inheritance of DataGridViewColumnHeaderCell, you can know that it inherits from the DataGridViewCell class, so only need to rewrite the DataGridViewColumnHeaderCell class of the Paint method, Draw a checkbox to the cell with CheckBoxRenderer. You can add a checkbox with a full selection in the DataGridView column header. Here is the implementation code:

  

  Implementation code

 Public Delegate voidCheckboxclickedhandler (BOOLState );  Public classDatagridviewcheckboxheadercelleventargs:eventargs {BOOL_bchecked;  PublicDatagridviewcheckboxheadercelleventargs (BOOLbchecked) {_bchecked=bchecked; }         Public BOOLChecked {Get{return_bchecked;} }    }    classDatagridviewcheckboxheadercell:datagridviewcolumnheadercell {point checkboxlocation;        Size checkboxsize; BOOL_checked =false; Point _celllocation=NewPoint (); System.Windows.Forms.VisualStyles.CheckBoxState _cbstate=System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal;  Public EventCheckboxclickedhandler oncheckboxclicked;  PublicDatagridviewcheckboxheadercell () {}protected Override voidPaint (System.Drawing.Graphics Graphics, System.Drawing.Rectangle clipbounds, SYSTEM.DRAWING.R Ectangle Cellbounds,intRowIndex, DataGridViewElementStates datagridviewelementstate,Objectvalue,ObjectFormattedValue,stringErrorText, DataGridViewCellStyle cellstyle, DataGridViewAdvancedBorderStyle advancedbordersty Le, datagridviewpaintparts paintparts) {Base. Paint (Graphics, clipbounds, Cellbounds, RowIndex, datagridviewelementstate, value, Formatt            Edvalue, ErrorText, CellStyle, Advancedborderstyle, paintparts); Point P=NewPoint (); Size s=checkboxrenderer.getglyphsize (graphics, System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal); P.x= Cellbounds.location.x +(Cellbounds.width/2)-(S.width/2) ; P.Y= Cellbounds.location.y +(Cellbounds.height/2)-(S.height/2); _celllocation=cellbounds.location; Checkboxlocation=p; Checkboxsize=s; if(_checked) _cbstate=System.Windows.Forms.VisualStyles. Checkboxstate.checkednormal; Else_cbstate=System.Windows.Forms.VisualStyles. Checkboxstate.uncheckednormal;        Checkboxrenderer.drawcheckbox (Graphics, checkboxlocation, _cbstate); }        protected Override voidOnmouseclick (DataGridViewCellMouseEventArgs e) {point P=NewPoint (e.x + _celllocation.x, E.y +_CELLLOCATION.Y); if(p.x >= checkboxlocation.x && p.x <=checkboxlocation.x+Checkboxsize.width&& p.y >= checkboxlocation.y && p.y <=CHECKBOXLOCATION.Y+checkboxsize.height) {_checked= !_checked; if(Oncheckboxclicked! =NULL) {oncheckboxclicked (_checked);  This. Datagridview.invalidatecell ( This); }                            }             Base.        Onmouseclick (e); }         }

  

  Invocation mode

Newnew= cbheader;datagridview1. Columns.Add (COLCB);
cbheader.oncheckboxclicked + =     new Checkboxclickedhandler (cbheader_oncheckboxclicked);

 1. We only need to define a datagridviewcheckboxcolumn.

2. Then define a checkboxclicked event for each row of the checkbox.

  Test program

Create a WinForm project, add a DataGridView control, and initialize a few rows of default data. Note: Datagirdview has an edit state, and if there is a row of data in the edit state, that line is edited.

The solution is to add the EndEdit () call to the event's binding method.

     Public Partial classForm1:form { PublicForm1 () {InitializeComponent ();        Initdtsource (); }        Private voidCbheader_oncheckboxclicked (BOOLState ) {            //This is a very important sentence. End Edit StateDginfo.endedit (); DgInfo.Rows.OfType<DataGridViewRow> (). ToList (). ForEach (t = t.cells[0]. Value =State ); }        Private voidInitdtsource () {Try            {                var_dtsource =NewDataTable (); //1. Add Columns_dtsource.columns.add ("name",typeof(string));//data type is Text_dtsource.columns.add ("ID Number",typeof(string));//data type is Text_dtsource.columns.add ("Time",typeof(string));//data type is Text_dtsource.columns.add ("location",typeof(string));//data type is Text                 for(inti =0; I <Ten; i++) {DataRow drdata=_dtsource.newrow (); drdata[0] ="Test"+i; drdata[1] ="35412549554521263"+i; drdata[2] ="2017-05-21 10:55:21"; drdata[3] ="Beijing";                _dtsource.rows.add (Drdata); } Dginfo.datasource=_dtsource;            Initcolumninfo (); }            Catch(Exception ex) {}}Private voidInitcolumninfo () {intindex =0; Datagridviewcheckboxcolumn COLCB=NewDatagridviewcheckboxcolumn (); Datagridviewcheckboxheadercell Cbheader=NewDatagridviewcheckboxheadercell (); Colcb.headercell=Cbheader; Colcb.headertext="Select All"; Cbheader.oncheckboxclicked+=NewCheckboxclickedhandler (cbheader_oncheckboxclicked);            DgInfo.Columns.Insert (index, COLCB); Index++; Dginfo.columns[index]. HeaderText="name"; Dginfo.columns[index]. Width= -; Index++; Dginfo.columns[index]. HeaderText="ID Number"; Dginfo.columns[index]. Width= -; Index++; Dginfo.columns[index]. HeaderText="Time"; Dginfo.columns[index]. Width= Max; Index++; Dginfo.columns[index]. HeaderText="location"; Dginfo.columns[index]. Width= -; System.Windows.Forms.DataGridViewCellStyle DataGridViewCellStyle2=NewSystem.Windows.Forms.DataGridViewCellStyle (); Datagridviewcellstyle2.alignment= System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223,Datagridviewcellstyle2.forecolor =System.Drawing.Color.Blue; Datagridviewcellstyle2.selectionforecolor=System.Drawing.Color.Blue; Dginfo.columns[index]. DefaultCellStyle=DataGridViewCellStyle2; }    }

  Other

1. Reference Address: Https://www.codeproject.com/Articles/20165/CheckBox-Header-Column-For-DataGridView

2. Demo download

C # Summary (iii) DataGridView Add a Select all column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.