您需要處理ComboBoxValidating事件,然後將其添加到那裏。這裏有一些代碼:
private void HandleEditShowing(
object sender, DataGridViewEditingControlShowingEventArgs e)
{
var cbo = e.Control as ComboBox;
if (cbo == null)
{
return;
}
cbo.DropDownStyle = ComboBoxStyle.DropDown;
cbo.Validating -= HandleComboBoxValidating;
cbo.Validating += HandleComboBoxValidating;
}
private void HandleComboBoxValidating(object sender, CancelEventArgs e)
{
var combo = sender as DataGridViewComboBoxEditingControl;
if (combo == null)
{
return;
}
//check if item is already in drop down, if not, add it to all
if (!combo.Items.Contains(combo.Text))
{
var comboColumn = this.dataGridView1.Columns[
this.dataGridView1.CurrentCell.ColumnIndex] as
DataGridViewComboBoxColumn;
combo.Items.Add(combo.Text);
comboColumn.Items.Add(combo.Text);
this.dataGridView1.CurrentCell.Value = combo.Text;
}
}
所以當你處理EditingControlShowing事件時,鉤入組合框的Validating事件。然後,一旦用戶在DataGridView組合框中輸入了一些文本並將其跳出,該事件就會觸發。此時,您需要將其添加到組合框本身以及實際的DataGridViewColumn中,以便DataGridView中的所有其他行都具有該值。