当CurrentCell更改时,DataGridView ComboBox会丢失其值

时间:2015-11-28 00:17:59

标签: c# winforms datagridview datagridcomboboxcolumn

我有一个包含多列的DataGridView,第一列类型是Combobox。

当组合框选择发生变化时(通过鼠标点击或按键),我正在尝试关注下一个(第二个)单元格

我实际上是这样做的,但问题正是主题所说的:如果我干扰.CurrentCell以便聚焦到下一个单元格,则单元格内的组合框项目会丢失其值。

如果我按下< Enter&gt ;,它只保留其值或< Tab>更改组合框值后的键

DataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(DataGridView1_EditingControlShowing);

private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    e.CellStyle.BackColor = Color.Red;
    e.CellStyle.ForeColor = Color.White;

    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
    {
        Console.WriteLine("adding handler");
        ComboBox cmb = (ComboBox)e.Control;
        //cmb.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
        //cmb.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);

        cmb.SelectionChangeCommitted -= new EventHandler(cmb_SelectionChangeCommitted);
        cmb.SelectionChangeCommitted += new EventHandler(cmb_SelectionChangeCommitted);
    }

}
void cmb_SelectionChangeCommitted(object sender, EventArgs e)
{
    ComboBox cmb = (ComboBox)sender;
Console.WriteLine("Index #{0} Value:{1}", cmb.SelectedIndex.ToString(), cmb.SelectedValue.ToString()); //its working

    DataGridViewCell c = DataGridView1.CurrentCell; //get current cell
    DataGridView1.CurrentCell = DataGridView1[1, c.RowIndex]; //skips to next cell on the same row

    //here combobox lost its value after focusing on another cell!
}

1 个答案:

答案 0 :(得分:0)

好的,我明白了。我用SenKeys.Send来解决。