In winform, The datagridview interface can be described as a data display control with a large number of applications. You can use various controls in the datagridview interface.
There are already many. All of them instantiate a control and bind it through the datagridview. Controls. Add () method. Then, Data Binding and operations are performed through a specific operator.
The datagridview control is also used during project creation over the past few days, and the datagridview must use ComboBox to dynamically display data. I checked a lot
To complete the data binding of ComboBox in the datagridview, most of them are set by strictly setting in the form initializecomponent () in winform.
Bind data with the datasource, displaymember, and valuemember values of the ComboBox object. However, different data entries in each row are not allowed.
Bind rows. When viewing msdn, I found that an object is datagridviewcomboboxcell. As mentioned in msdn:
The datagridviewcomboboxcell class is a specialized type used to display the datagridviewcell control (that is, combining the edit field of the selected field in the list.
The currently selected datagridviewcomboboxcell carries a datagridviewcomboboxeditingcontrol, where you can change the cell value
(Assume that the readonly attribute of the cell is set to false ). Unlike the ComboBox control, the datagridviewcomboboxcell does not have selectedindex
And selectedvalue properties. Instead, you can select a value from the drop-down list to set the value attribute of a cell.
So I implemented this:
When you bind data to a dview, you can use for to cyclically Add rows (the functions cannot be completed when datasource is used ).
Fill null in the datagridviewcomboboxcolumn. Then add the ComboBox data binding code to the rowsadded event of the datagridview.
1 private void maid (Object sender, maid E)
2 {
3
4 datagridviewcomboboxcell dgvcell = This. datagridview1.rows [E. rowindex]. cells [1] As datagridviewcomboboxcell;
5 dgvcell. datasource = datasource;
6 dgvcell. displaymember = "measurename ";
7 dgvcell. valuemember = "measureid ";
8}
This completes data binding. You can add a button column next to the row of the datagridvie, and select the cellclick event of the datagridview cellto write code.
We can use
String selectvalue = (string) (This. datagridview1.rows [E. rowindex]. cells [1] As datagridviewcomboboxcell). value; // obtain the key of the selected value, that is, the value bound to valuember.
MessageBox. Show ("" + selectvalue. tostring () + "");
Note that if you bind a generic set, the value of displaymember and valuemember must be a property)
It cannot be a field of the class (filed ).