Windows · 2010-05-25

(收集)winform datagridview 指定列使用COMBOBOX

处理DataGridViewComboBoxCell的DataGridViewComboBoxEditingControl类的事件,
DataGridViewComboBoxEditingControl类继承自ComboBox类,事件都差不多的.

例如:下面的代码示例演示如何使用   DataGridView.EditingControlShowing   事件处理程序添加   DataGridViewComboBoxEditingControl   事件的处理程序。在这个示例中,编辑控件被强制转换为   ComboBox   以处理   ComboBox.SelectedIndexChanged   事件。
private   DataGridView   dataGridView1   =   new   DataGridView();

private   void   AddColorColumn()
{
DataGridViewComboBoxColumn   comboBoxColumn   =
new   DataGridViewComboBoxColumn();
comboBoxColumn.Items.AddRange(
Color.Red,   Color.Yellow,   Color.Green,   Color.Blue);
comboBoxColumn.ValueType   =   typeof(Color);
dataGridView1.Columns.Add(comboBoxColumn);
dataGridView1.EditingControlShowing   +=
new   DataGridViewEditingControlShowingEventHandler(
dataGridView1_EditingControlShowing);
}

private   void   dataGridView1_EditingControlShowing(object   sender,
DataGridViewEditingControlShowingEventArgs   e)
{
((ComboBox)e.Control).SelectedIndexChanged   +=
new   EventHandler(ComboBox_SelectedIndexChanged);
}

private   void   ComboBox_SelectedIndexChanged(object   sender,   EventArgs   e)
{
((ComboBox)sender).BackColor   =   (Color)((ComboBox)sender).SelectedItem;
}

// Set DataGridView Combo Column for CarID field
DataGridViewComboColumn ColumnCar = new DataGridViewComboColumn();
// DataGridView Combo ValueMember field name is “CarID”
// DataGridView Combo DisplayMember field name is “Car”
ColumnCar.DataPropertyName = “CarID”;
ColumnCar.HeaderText = “Car Name”;
ColumnCar.Width = 80;
// Bind ColumnCar to Cars table
ColumnCar.box.DataSource = ds.Tables[“Cars”];
ColumnCar.box.ValueMember = “CarID”;
ColumnCar.box.DisplayMember = “Car”;
// Add ColumnCar onto DataGridView layout
DataGridView1.Columns.Add(ColumnCar);