C# – Set DataGridView cell value and add a new row

cdatagridviewwinforms

I have a DataGridView with two columns. When a cell in the first column is clicked, an OpenFileDialog is shown and when I select a file, the cell in the second column value is set to the selected file name. Here is the code:

private void dataGridView1_CellContentClick(
    object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        SelectFile(e.RowIndex);
    }
}

private void SelectFile(int rowIndex)
{
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        dataGridView1.Rows[rowIndex].Cells[1].Value =
            openFileDialog.FileName;
    }
}

This works, but I would like a new row to be added when the cell value is set. This happens when I edit the cell manually, the row gets in 'edit' state and a new row is added below. I would like the same to happen when I set the cell value programmatically.

[edit]

When my form is first shown the DataGridView is empty and the only row is shown is the one with (* sign – IsNewRow is true). When I manually edit a cell in that row it goes into edit state (pencil sign) and a new empty row is added. This doesn't happen when I use the above code. The row remains as IsNewRow (* sign) and a new row is not added.

enter image description here
enter image description here

Best Answer

With this code you can do what you want to do. I Used it for the same reason:

myGrid.NotifyCurrentCellDirty(true);

Source of this answer: Make new row dirty programmatically and insert a new row after it in DataGridView

Related Topic