代码之家  ›  专栏  ›  技术社区  ›  TomáÅ¡ Zato

在DataGridViewComboBox单元格中选择另一项时立即发生事件

  •  0
  • TomáÅ¡ Zato  · 技术社区  · 6 年前

    我从如下列表初始化单元格:

    DataGridViewRow row = new DataGridViewRow();
    List<string> itemNames = new List<string>(new string[]
    {
        "ITEM 1",
        "ITEM 2",
        "ITEM 3",
        "Add new item..."
    });
    row.CreateCells(myDataGridView);
    row.Cells[0].Value = "";
    if(row.Cells[1] is DataGridViewComboBoxCell cell2)
    {
        cell2.DataSource = itemNames;
    }
    

    在真正的程序中,列表是从某个地方加载的 "Add new item..." 在末尾添加条目。我想要的是在 “添加新项目…” 在组合框中选择。

        protected void checkIfNewItemSelected(DataGridViewComboBoxCell combocell)
        {
            if (combocell.Value + "" == ADD_CONFIG_TEXT)
            {
                // do something to add new item (show a form)
            }
        }
    

    但是,我找不到在用户选择值后立即触发的任何合适事件。例如我试过 CellEndEdit CurrentCellDirtyStateChanged 在数据网格上。只有在组合框失去焦点后,才会触发这两个事件。特别是 latter is recommended by MSDN :

        private void dataGridViewConfigs_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            DataGridViewCell cell = dataGridViewConfigs.CurrentCell;
            // handle trigger for new PRJ config request
            if (cell is DataGridViewComboBoxCell combocell)
            {
                checkIfNewItemSelected(combocell);
            }
        }
    

    所以如果你选择 “添加新项目…” ,这就是你最终看到的:

    enter image description here

    只有当你点击其他地方,我尝试的事件才会被触发。我需要立即采取行动后,用户点击这个特定的条目。

    怎么做?

    1 回复  |  直到 6 年前
        1
  •  1
  •   steve16351    6 年前

    您可以直接连接到编辑控件上的事件,例如。。。

    private const string NEW_ITEM_TEXT = "Add new item..";
    
    private void Form1_Load(object sender, EventArgs e)
    {
        var comboCol = new DataGridViewComboBoxColumn();
        comboCol.Items.AddRange("A", "B", NEW_ITEM_TEXT);
        dataGridView1.Columns.Add(comboCol);
        dataGridView1.EditingControlShowing += DataGridView1_EditingControlShowing;            
    }
    
    private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        var comboBox = e.Control as ComboBox;
        if (comboBox == null) return;
        comboBox.SelectedIndexChanged -= ComboBox_SelectedIndexChanged;
        comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
    }
    
    private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataGridViewComboBoxEditingControl editor = sender as DataGridViewComboBoxEditingControl;
        if (editor.SelectedItem.ToString() != NEW_ITEM_TEXT) return;
        Form2 f2 = new Form2();
        f2.Show();
    }