C# DataGridView中DataGridViewComboBox下拉选择事件方法(包括更改DataGridViewComboBox点击两次变为点击一次)

1,更改DataGridViewComboBoxColumn点击两次变为点击一次

    private void dataGridView2_CellEnter_1(object sender, DataGridViewCellEventArgs e)
    {
        index = e.RowIndex;
        //实现单击一次显示下拉列表框
        if (dataGridView2.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && e.RowIndex != -1)
        {
            SendKeys.Send("{F4}");
        }
    }

2,DataGridView中DataGridViewComboBox下拉选择事件方法

    /**
    **第一步:
    **/
    ComboBox cbo = new ComboBox();
    void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (dataGridView2.CurrentCell.OwningColumn.Name == "列的名称" && dataGridView2.CurrentCell.RowIndex != -1)
        {
          //保存当前的事件源。为了触发事件后。在取消
            cbo = e.Control as ComboBox;
            cbo.SelectedIndexChanged += new EventHandler(cbo_SelectedIndexChanged);  
        } 
    }
    /**
    **第二步:
    **/
    void cbo_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox combox = sender as ComboBox;
        //添加离开combox的事件(重要;)
        combox.Leave += new EventHandler(combox_Leave);
        try
        {
            //在这里就可以做值是否改变判断
            if (combox.SelectedItem != null)
            {
                //这里写触发后是逻辑代码
            }   
        }
        catch (Exception ex)
        {
        }
    }
    
    /**
    **第三步:离开combox时,把事件删除
    **/
    public void combox_Leave(object sender, EventArgs e)
    {
        ComboBox combox = sender as ComboBox;
        //做完处理,须撤销动态事件
        combox.SelectedIndexChanged -= new EventHandler(cbo_SelectedIndexChanged);
    }

你可能感兴趣的:(C#,C#)