引言
需求:在表格中的下拉框选择完成后,立即改变其他列中的value。
由于DatagridView中使用comboBoxColumn,只有在选择完下拉框的值,并且点击其他位置,才会触发DatagridView的cellValueChanged事件,才能改变其他列的值,效果并不理想。
实现
流程大致如下
实现示例
可复制代码,根据需求进行修改
1、在设计器中创建一个DatagirdView控件
2、在代码中实现如下
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataTable typedt = new DataTable();
typedt.Columns.Add("typeid", typeof(int));
typedt.Columns.Add("typename");
typedt.Columns.Add("typedescription");
typedt.Rows.Add(0, "Typed 0", "description0");
typedt.Rows.Add(1, "Typed 1", "description1");
typedt.Rows.Add(2, "Typed 2", "description2");
typedt.Rows.Add(3, "Typed 3", "description3");
typedt.Rows.Add(4, "Typed 4", "description4");
typedt.AcceptChanges();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("type", typeof(int));
dt.Columns.Add("typedescription");
for (int i = 0; i < 50; i++)
{
dt.Rows.Add(i.ToString("000"), "name" + i, i % 4);
}
dt.AcceptChanges();
this.dataGridViewX1.DataSource = dt;
this.dataGridViewX1.Columns.RemoveAt(2);
DataGridViewComboBoxColumn cbc = new DataGridViewComboBoxColumn();
cbc.DataPropertyName = "type";
cbc.DisplayMember = "typename";
cbc.ValueMember = "typeid";
cbc.DataSource = typedt;
cbc.HeaderText = "Type";
this.dataGridViewX1.Columns.Insert(2, cbc);
this.dataGridViewX1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
this.dataGridViewX1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}
DataTable dt = new DataTable();
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (cbm != null)
{
cbm.SelectedIndexChanged -= new EventHandler(cbm_SelectedIndexChanged);
}
}
ComboBox cbm;
DataGridViewCell currentCell;
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox)
{
cbm = (ComboBox)e.Control;
if (cbm != null)
{
cbm.SelectedIndexChanged += new EventHandler(cbm_SelectedIndexChanged);
}
currentCell = this.dataGridViewX1.CurrentCell;
}
}
void cbm_SelectedIndexChanged(object sender, EventArgs e)
{
this.BeginInvoke(new MethodInvoker(EndEdit));
}
void EndEdit()
{
if (cbm != null)
{
DataRowView drv = cbm.SelectedItem as DataRowView;
if (drv != null)
{
this.dataGridViewX1[currentCell.ColumnIndex + 1, currentCell.RowIndex].Value = drv[2].ToString();
this.dataGridViewX1.EndEdit();
}
}
}
}
效果
typedescription列中的数值,可以立即跟随Type列的选择值变化而立即更新