DataGridViewComboBoxColumn - 访问ComboBox以附加click事件

时间:2015-10-12 09:39:09

标签: c# winforms datagridview datagridviewcombobox

我想创建DataGridViewComboBoxColumn并附加到它的组合框Click事件(我想在点击时生成它的数据源)。

1 个答案:

答案 0 :(得分:2)

虽然我不知道你为什么需要Click ComboBox控件的事件, 您可以使用EditingControlShowing事件访问该组合框:

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
}

但是您应该知道,您也可以在datagridview的DataSource事件中为您设置CellClick

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   
    }
}

另一个重要的事情是,如果您设置的数据源不包含此列的一个单元格的值,则在渲染列时会收到错误。