DataGridViewComboBoxColumn - access ComboBox to attach click event

China☆狼群 提交于 2019-12-24 12:31:07

问题


I want to create DataGridViewComboBoxColumn and attach to it's combo box Click event (i want to generate it's datasource on click only).


回答1:


While I have no idea about why you need Click event of that ComboBox control, you can access that combo box using EditingControlShowing event:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    //Check if the event is for your column, for example column 1
    if (this.dataGridView1.CurrentCell.ColumnIndex == 1)
    {
        var comboBox = e.Control as DataGridViewComboBoxEditingControl;
        comboBox.Click -= comboBox_Click;
        comboBox.Click += comboBox_Click;
    }
}

private void comboBox_Click(object sender, EventArgs e)
{
    var comboBox = sender as DataGridViewComboBoxEditingControl;
    //use comboBox here
}

But you should know, you can set the DataSource for you column in CellClick event of your datagridview too:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if(e.ColumnIndex==1 && e.RowIndex>-1)
    {
        //Check if the event is for your column, for example column 1
        var column = (DataGridViewComboBoxColumn)this.dataGridView1.Columns[e.ColumnIndex];
        //use column.DataSource   
    }
}

And another important thing you should know is if you set a datasource that not contains the value of one of cells of this column, you will receive errors while rendering the column.



来源:https://stackoverflow.com/questions/33077863/datagridviewcomboboxcolumn-access-combobox-to-attach-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!