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:

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.

I was trying to do it with Add method but row is added to the first position. The only solution I can think of is to add new row and than swap values with current one. Probaj, možda uspe :)
–
ValeMay 26 '11 at 6:32

Yes, I may have to do that, but it just seemed logical that a new row gets added even if I edit the first one with code. Hvala na komentaru.
–
Uros CalakovicMay 26 '11 at 14:26

Yes, obviously it's a "feature"(not to say bug) of DataGridView. Maybe there is a reason for that. Try asking on msdn. Srećno!
–
ValeMay 30 '11 at 10:44

I ran into the same problem, too. I did something like the following, it just works!!! (.Net framework 4.5)

// Set value for some cell, assuming rowIndex refer to the new row.
dateGridView1.Rows[rowIndex].Cells[1].Value = "Some Value";
// Then simply do this:
dataGridView1.BeginEdit(true);
dataGridView1.EndEdit();

I searched for the solution how I can insert a new row and How to set the individual values of the cells inside it like Excel. I solved with following code:

dataGridView1.ReadOnly = false; //Before you modify it, it should be set to false!
dataGridView1.Rows.Add(); //This inserts first row, index is "0"
dataGridView1.Rows[0].Cells[0].Value = "this is 0,0!"; //This line will set the right hand string to the very first cell of your datagridview.

Note:
1. Previously I have designed the columns in design mode.
2. I have set the row header visibility to false from property of the datagridview.

Basically the user clicks a button on the DataGridView, it opens a dialog which asks questions, then fills the row out. Just for the fun of it, I fixed it by using SendKeys to get the row in edit mode instead of new mode. You don't have to use SendKeys to fill out the entire row, just one cell is enough to make it work.

Two important things to note. First the datagridview needs to have multiselect off, or you need to unselect the current cell(s). Second, you need the defaultvaluesneeded event to work and fill the grid with sane data.