如何获取DataGridViewComboboxColumn SelectedIndex按键事件?

时间:2014-02-10 07:01:45

标签: c# winforms

我有一个带有组合框的DataGridview。

我可以使用以下代码获取组合框的选定索引:

private void dg_errorchart_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        try
        {
            if (e.Control is DataGridViewComboBoxEditingControl)
            {
                ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
                ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
                ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            }

            ComboBox cmbBx = e.Control as ComboBox;             

            if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
            {
                ComboBox comboBoxCell = (ComboBox)e.Control;
                if (comboBoxCell != null)
                {                       
                    comboBoxCell.SelectionChangeCommitted -= new EventHandler(comboBoxCell_SelectionChangeCommitted);

                    comboBoxCell.SelectionChangeCommitted += new EventHandler(comboBoxCell_SelectionChangeCommitted);                      
                }
            }

        }
        catch (Exception ex)
        {

        }
    }

但问题是如果通过键盘选择它,我无法获得组合框的索引。我怎么能这样做?

更新:

我刚为combobox添加了另一个事件处理程序,并手动捕获输入并增加行ID。

cmbBx.KeyUp -= new KeyEventHandler(cmbBx_KeyUp);
cmbBx.KeyUp += new KeyEventHandler(cmbBx_KeyUp);

在我添加的事件处理程序中:

DataGridViewCell currentCell = dg_errorchart.CurrentCell;
if (currentCell != null)
{
    DataGridViewComboBoxEditingControl cmbBx = sender as DataGridViewComboBoxEditingControl;
    if (cmbBx.SelectedIndex >= 0)
    {
        int nextRow = 0;
        nextRow = currentCell.RowIndex + 1;
        if (nextRow >= dg_errorchart.Rows.Count)
        {
            nextRow = nextRow - 1;
        }

        DataGridViewCell nextCell = dg_errorchart.Rows[nextRow].Cells[6];
        dg_errorchart.CurrentCell = nextCell;
    }
}

谢谢

Suressh

1 个答案:

答案 0 :(得分:0)

您是否尝试在 SelectedIndexChanged 事件处理程序中处理此问题?

将SelectedIndexChanged事件处理程序添加到dg_errorchart_EditingControlShowing方法中,与 SelectionChangeCommitted 处理程序位于同一位置。

comboBoxCell.SelectedIndexChanged -= new EventHandler(comboBoxCell_SelectedIndexChanged);
comboBoxCell.SelectedIndexChanged += new EventHandler(comboBoxCell_SelectedIndexChanged);

然后在comboBoxCell_SelectedIndexChanged方法中,您将能够从组合框中获取选定的索引或值。

private void comboBoxCell_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox conboBox = (ComboBox)sender;
    int index = conboBox.SelectedIndex;
    if (index > -1)
    {
        label1.Text = conboBox.SelectedValue + ": " + conboBox.Text;
    }
}

虽然用户通过键盘选择了一个项目,但这对我有用。