Dannz
Dannz

Reputation: 495

dataGridView change cell datasource and type

After I click a particular row and I click a button, I want to change the cell type from default type (DataGridViewTextBoxCell) to DataGridViewComboBoxCell and to change that cell data source to a list.

Somehow I encountered an unexplained behavior, In one line it works and shows the ComboBox, in other, it just enters to edit mode.

My code looks something like this:

 private void btnClick(object sender, EventArgs e)
 {
    dataGridView.BeginEdit(true);

    var selectedRow = CurrentCell.RowIndex;
    var selectedColumn = CurrentCell.ColumnIndex;
    var cellName = dataGridView[0, _selectedCell.RowIndex].Value.ToString();
    var dict = GetDict(cellName);

    if (dict != null)
    {
       var comboBoxCell = new DataGridViewComboBoxCell
       {
           DataSource = dict.Keys.ToList()
       }
       dataGridView[1, selectedRow] = comboBoxCell;
       dataGridView.CurrentCell = dataGridView.Rows[selectedRow].Cells[selectedColumn];
    }
    dataGridView.BeginEdit(false);
}

Update: It seems only after the event CellBeginEdit is fired, which is caused by pressing other cell it updates, But then it takes like 3-4 click for the ComboBox to open.

Upvotes: 0

Views: 384

Answers (1)

Waseem Ahmad Naeem
Waseem Ahmad Naeem

Reputation: 890

Try This Code. You should override CellClick Event or Call You Method There. This code is written in CellClick Event, Don't get confused with Name

//This Code is written in CellClick Event not in CellContentClick (Don'tconfuse with signature)
    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            dataGridView1.BeginEdit(true);
            var selectedRow = (sender as DataGridView).CurrentCell.RowIndex;
            var selectedColumn = (sender as DataGridView).CurrentCell.ColumnIndex;
            var comboBoxCell = new DataGridViewComboBoxCell
            {

            };
            dataGridView1.CurrentCell = dataGridView1.CurrentCell as DataGridViewComboBoxCell;
            dataGridView1[selectedColumn, selectedRow] = comboBoxCell;
            dataGridView1.CurrentCell = dataGridView1.Rows[selectedRow].Cells[selectedColumn];
           dataGridView1.BeginEdit(false);
        }

Upvotes: 1

Related Questions