[WinForm] DataGridView Binding datatable,combobox Column bindings dictionary

Source: Internet
Author: User

A Demand introduction

Generally like enumerated types of data, we store in the database such as (1, 2, 3, 4 ... ) or ("001", "002", "003" ... This class, but the interface we want to display is specific text content, so that users understand the use. So when data that is loaded from a database DataTable is bound to DataGridView, some of these enumeration columns are required to take a drop-down box and bind the corresponding enumerated data source.

Two concrete Realization

First, if DataGridView's AutoGenerateColumns is true, the columns in the bound data are automatically generated when the DataTable is bound to DataGridView, and the default is normal Dat Agridviewtextboxcolumn . So if you want to set the drop-down column in DataGridView, first set the AutoGenerateColumns to false.

1 // <summary>2 // Sample3 /// DataGridView bind datatable,combobox Column binding enum enum4 // </summary>5  PublicMainForm ()6{7InitializeComponent ();8 9DataTable datatable = Createdatatable ();TenDatagridview.autogeneratecolumns =true;//Default settings OneDatagridview.datasource = dataTable; A     //Setgridview (dataTable); -} -  the // <summary> - /// Build a data source - /// can be read from the database to build a DataTable data source - // </summary> + /// <returns>datatable data Sheet </returns> -  PublicDataTable createdatatable () +{ ADataTable dt =NewDataTable (); atDt. Columns.Add (NewDataColumn ("Id",typeof(int))); -Dt. Columns.Add (NewDataColumn ("Name",typeof(string))); -Dt. Columns.Add (NewDataColumn ("EnumCol1",typeof(int))); -Dt. Columns.Add (NewDataColumn ("EnumCol2",typeof(string))); -Random r =NewRandom (); -      for(inti = 0; I < 50; i++) in{ -DataRow dr = dt. NewRow (); toDr[0] = R.next (); +DR[1] = "Name ="+ R.next (); -DR[2] = R.next (1, 5); theDR[3] = "Enumcol_"+ r.next (1, 5); *Dt. Rows.Add (DR); $}Panax Notoginseng  -     returnDt the}
View Code

(AutoGenerateColumns = True):

After setting the AutoGenerateColumns property to False, the columns are generated manually. Where the EnumCol1 column is bound to an enumeration type,EnumCol2 to bind a dictionary type (dictionary<string, string>).

1 // <summary>2 /// Enumeration 13 // </summary>4 Private enumEnumCol15{6A = 1,7B = 2,8C = 3,9D = 4,TenE = 5 One} A // <summary> - /// enumeration to Dictionary - // </summary> the /// <typeparam name= "T" ></typeparam> - /// <param name= "Enumtype" ></param> - // <returns></returns> - Privatedictionary<int,string> enumtodictionary (Type enumtype) +{ -dictionary<int,string> result =Newdictionary<int,string> (); +     foreach(intKeyinchEnum.getvalues (Enumtype)) A{ at         string value= Enum.getname (enumtype, key); -Result. ADD (Key,value); -} -  -     returnResult -}

The Enumtodictionary method in the preceding code converts the enumeration type to a dictionary type so that data binding can be processed uniformly.

1 // <summary>2 /// set DataGridView View3 // </summary>4 // <param name= "DT" > Data source table </param>5  Public voidSetgridview (DataTable DT)6{7     //When a column is automatically generated when the binding is discarded, and the DataGridView column is not initialized8     //Manually generate columns9     if(!datagridview.autogeneratecolumns && DataGridView.Columns.Count = = 0)Ten{ Onedictionary<int,string> dic = enumtodictionary (typeof(EnumCol1)); A         foreach(DataColumn DCinchDt. Columns) -{ -             stringcolname = DC. ColumnName; theDataGridViewColumn DGVC =NULL; -             if(Colname.startswith ("Enumcol"))//Generate drop-down columns -{ -DGVC =NewDatagridviewcomboboxcolumn (); +BindingSource bs =NewBindingSource (); -                 if(Colname.endswith ("1"))//Bind enumeration 1 +{ ABs. DataSource = dic; atDGVC. ValueType =typeof(int); -} -                 Else if(Colname.endswith ("2"))//Bind enumeration 2 -{ -Bs. DataSource =Newdictionary<string,string> () -{ in{"Enumcol_1", "AA"}, -{"enumcol_2", "BB"}, to{"Enumcol_3", "CC"}, +{"Enumcol_4", "DD"}, -{"enumcol_5", "EE"} the}; *DGVC. ValueType =typeof(string); $}Panax Notoginseng((Datagridviewcomboboxcolumn) DGVC). DisplayMember = "Value"; -((Datagridviewcomboboxcolumn) DGVC). ValueMember = "Key"; the((Datagridviewcomboboxcolumn) DGVC). DataSource = BS; +((Datagridviewcomboboxcolumn) DGVC). Displaystyle = datagridviewcomboboxdisplaystyle.nothing; A((Datagridviewcomboboxcolumn) DGVC). FlatStyle = FlatStyle.Flat; the} +             Else//Generate normal columns -{ $DGVC =NewDatagridviewtextboxcolumn (); $} -DGVC. Name = colname; -DGVC. DataPropertyName = colname;//Ensure that the value of this column is bound to the ColName column in the DataTable theDATAGRIDVIEW.COLUMNS.ADD (DGVC); -}Wuyi} the} - 

You need to pass BindingSource when the column type is datagridviewcomboboxcolumn and you want to bind the dictionary data Source (Dictionary). That

New BindingSource (); Bs. DataSource = dic; ((Datagridviewcomboboxcolumn) DGVC). DataSource = BS;

Special attention is paid to the ==>

48 Lines of code:

DGVC.  DataPropertyName = colname; The value binding that represents the drop-down column corresponds to the colname column data in the data source DataTable;

37 lines, 38 lines of code:

((Datagridviewcomboboxcolumn) DGVC). DisplayMember = "Value";

((Datagridviewcomboboxcolumn) DGVC). ValueMember = "Key";

DisplayMember is a location that represents the value of the drop-down box that is bound to the DGVC data source (the value of the dictionary);

ValueMember is a location (the dictionary key) that represents the actual value of the drop-down box bound to the DGVC data source;

23 Lines, 35 lines of code:

DGVC. ValueType = typeof(int);

DGVC. ValueType = typeof(string);

These two sentences specify the type of the column in the data source that the column is bound to. At this point, you must ensure that the value type of the column in the data source DataTable must be the same as the data source type that the column's ValueMember property is bound to. In the example, the data type of the DataGridView column EnumCol1 and column EnumCol2 must be the same as the key type of the Dictionary being bound (because DGVC's ValueMember attribute is bound to key).

Three additional sentences

1. The difference between the INTEGER and INT types in the SQLite database needs to be determined by "tools–> options–> type Mappings".

However, in practice, where the INT type is corresponding to the C # Int32, if you bind an INTEGER column to Dictionary<int, string>, the following error is reported:

2, this article to datagridviewcomboboxcolumn column binding Dictionary dictionary data source as an example to illustrate the specific binding details, of course, the Type column can also be bound to other types of data such as DataTable, as long as the binding details are set.

3, as for the landlord on the Internet to find relevant resources, there are many people (all the most) mentioned to bind the Datagridviewcomboboxcolumn data source and then bind the DataGridView data source can solve the above exception, And this answer paste full network is, but the landlord originally tried no matter which in front of which after all is not, harm the landlord doubts long time own IQ, ⊙︿⊙! Finally, use GOOGLEFQ to find an English forum in English reply just know where is the key to this anomaly! How to say, this unverified solution in the Chinese network is spread everywhere, and at a glance know is the kind of paste copied over, there is no other note description.

There is a saying that it is reasonable, the programmer is very hard, often overtime to stay up to what, we programmers themselves why difficult programmer? You dig a hole for others, others also give you dig a pit, OK, we this industry is here to play jump pit, crawl pit of retarded game bar, then let other industry ridicule despise us! Why not! Still want to publish or forward a solution, can first verify its correctness, and then make its own comments, at least to be worthy of this job, worthy of other programmers, less to others dig pits, others also give you less digging pits, so what worry what bug can't solve, Why worry more than pay so much not to work hard to solve a problem that others have solved well?

Four Resources download

Sample project: Http://files.cnblogs.com/files/memento/DataGridView_ComboBoxColumnSample.zip

[WinForm] DataGridView Binding datatable,combobox Column bindings dictionary

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.