2

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

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
user3662546
  • 87
  • 12
  • The post answers to your requirement to attach a handler to click event of that combo box, but I recommend you to set data source of your `ComboBoxColumn` in `Load` event of form. – Reza Aghaei Oct 12 '15 at 12:45
  • You could also attach to `DataGridView.CellContentClick` and handle it for the column index of the ComboBox column. But I agree with the warnings Reza has provided. – OhBeWise Oct 12 '15 at 15:01
  • @user3662546 When you find an answer helpful, you can kindly click the check mark near the question to accept it. You can only accept one answer while you can vote up as many answer as you find helpful including accepted one by click on up arrow. This way you make the answers more helpful. You can also vote up for good questions. :) – Reza Aghaei Oct 13 '15 at 16:19

1 Answers1

3

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.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Thanks for answer, it works (I used the option with CellClick). I needed that because datasource contains ~2900 records taken from webservice, which takes time. While combobox is always visible for users, using it is optional, so I didn't want to load it unnecessarily. – user3662546 Oct 14 '15 at 07:03
  • @user3662546 You are welcome:) Good idea, another idea that you can consider for next times, is loading data async. – Reza Aghaei Oct 14 '15 at 08:14