Search code examples
c#datagridviewcolumn

DGV ComboBox Cell remain updateable


I have a DataGridView that I want users to be able to add records to directly. This is done by clicking a link beneath the DGV, at which point a new row is programmatically added, and the first visible cell is of ComboBoxCell type. Code excerpt for how I'm doing this is:

// Add a new row to DGV
DataGridView dgv = this.dgvInformation;
DataGridViewRow newRow = new DataGridViewRow();
dgv.Rows.Add(newRow);

// Create cells and add to row
DataGridViewComboBoxCell cellInfoType = new DataGridViewComboBoxCell();
newRow.Cells["InfoType"] = cellInfoType;

// Create DataSource based off LINQ query here
List<ComboItemAccountInfoType> comboDataSource = new List<ComboItemAccountInfoType>();
// List is populated here

// Assign DataSource to combo cell
cellInfoType.DataSource = comboDataSource;
cellInfoType.ValueMember = "AccInfoTypeID";
cellInfoType.DisplayMember = "InfoType";

// Scroll new row into view and begin editing
dgv.FirstDisplayedScrollingRowIndex = dgv.Rows.Count - 1;
dgv.CurrentCell = dgv[1, dgv.Rows.Count - 1];
dgv.BeginEdit(true);

The DataSource contains some values with an ID of -1, which are categories that the user should not be able to select, and all other values have their valid database ID. This all works fine, except that if a user has selected a -1 row I am unable to keep the combo cell in edit more, as it simply stores the value in the cell and I can no longer activate the drop-down. I have added the following code to the _CellValueChanged event, but it has no effect:

private void dgvInformation_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dgv = this.dgvInformation;
    DataGridViewCell cell = dgv[e.ColumnIndex, e.RowIndex];

    // If type of cell is ComboBox then 
    if (cell.GetType() == typeof(DataGridViewComboBoxCell))
    {
        DataGridViewComboBoxCell cellInfoType = (DataGridViewComboBoxCell)cell;

        if ((int)cellInfoType.Value == -1)
        {
            MessageBox.Show("Going back into edit mode...");
            dgv.CurrentCell = cell;
            dgv.BeginEdit(true);
        }
        else
        {
            MessageBox.Show(cellInfoType.Value.ToString());
        }
    }
}

I do get the "Going back into edit mode..." message here after moving onto another cell, but it doesn't then do what it says! Could anyone please explain why it won't go back into edit mode, or is there a way of preventing the value becoming locked as soon as it has been selected?

Many thanks!


Solution

  • There should be a "validating" event for you to intercept and cancel if the value is -1.