Recently, the datagridview is used. The most profound thing is its event. I think many people want to edit the table unit and update other things at the same time, just like the textchanged event of Textbox, but the datagridview does not provide events like textchanged. I would like to use the following example to illustrate how to achieve real-time update.
The preceding form has a dview instance datagridview1 and a label instance label1. Datagridview1 has three fields: the class (datagridviewcomboboxcolumn), the name (datagridviewtextboxcolumn), and the score (datagridviewtextboxcolumn ).
To achieve this effect, if you change the value of any cell in the datagridview1, the text of label1 is updated to the value of the cell. The Code is as follows:
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
This. Maid + =
New maid (maid );
}
// Events triggered when the cell is edited
Void datagridview1_editingcontrolshowing (Object sender, datagridvieweditingcontrolshowingeventargs E)
{
If (E. Control. GetType (). Equals (typeof (datagridviewcomboboxeditingcontrol) // when the cell class is ComboBox
{
E. cellstyle. backcolor = color. fromname ("window ");
Datagridviewcomboboxeditingcontrol editingcontrol = E. Control as datagridviewcomboboxeditingcontrol;
Editingcontrol. selectedindexchanged + = new eventhandler (editingcontrol_selectedindexchanged );
}
Else if (E. Control. GetType (). Equals (typeof (datagridviewtextboxeditingcontrol) // when cell is textbox-like
{
E. cellstyle. backcolor = color. fromname ("window ");
Datagridviewtextboxeditingcontrol editingcontrol = E. Control as datagridviewtextboxeditingcontrol;
Editingcontrol. textchanged + = new eventhandler (editingcontrol_textchanged );
}
}
// Textchanged event of textbox
Void editingcontrol_textchanged (Object sender, eventargs E)
{
This. label1.text = maid. tostring ();
}
// Selectedindexchanged event of combox
Void editingcontrol_selectedindexchanged (Object sender, eventargs E)
{
This. label1.text = maid. tostring ();
}
}
Some notes
1. editingcontrolshowing is an event that comes with the dview. This event is triggered when a cell is edited. Then we get to the datagridview1_editingcontrolshowing function, and then (if... Else if ...) Determine whether the cell is a datagridviewcomboboxeditingcontrol or a datagridviewtextboxeditingcontrol control. After determining the control type, you can use the built-in events of this type, such as the selectedindexchanged event that comes with the datagridviewcomboboxeditingcontrol.
2. Why do we use datagridview1.currentcell. editedformattedvalue instead of datagridview1.currentcell. Value? Because the value of the cell in the editing state is not updated at the same time, our change is its editedformattedvalue. Of course, this difference is advantageous.
3. Why should I add E. cellstyle. backcolor = color. fromname ("window ")? Practice is the standard for testing truth. It is clear to remove this sentence.
Below is: