none
Adding a New Row to DataGridView RRS feed

  • Question

  • Hi,

     

    In order to programmatically add a new row to a DataGridView I used till now the following code:

     

    int iTableRowIndex = my_table.Rows.Add(); // exception!

    DataGridViewRow dgvr = my_table.Rows[iTableRowIndex];

    dgvr.Cells["Header1"].Value = "value1";

    ...

     

    But now, as my OnNewRowsAdded() was changed so that it causes an exception if called (in result of calling the mytable.Rows.Add method as done above) before all the rows of the newly added row are properly set, I had to abandon above code, and actually add the new row to the table only after properly setting its cells.

     

    So  I tried the following code:

     

    DataGridViewRow dgvr = new System.Windows.Forms.DataGridViewRow();

    dgvr.CreateCells(my_table);

    dgvr.Cells["Header1"].Value = "value1"; // Argument exception -- Column named Header1 cannot be found!

    ...

    my_table.Rows.Add(dgvr);

     

    But here an exception occurs when setting values to the cells (see the remark in the code).

     

    How can I programatically create, set, and later add a new row to a DataGridView for which a set of columns has been already created? (Please assume I must do it this way.)

     

    Thanks,

    Ofer.

     

    Thursday, February 21, 2008 10:25 AM

Answers

  • Hi,

    To resolve your problem you can try this

    Int32 columnNum = 1;
    DataGridViewRow dgvr = new System.Windows.Forms.DataGridViewRow();
    dgvr.CreateCells(dataGridView1);
    dgvr.Cells[columnNum].Value = "value1";
    dataGridView1.Rows.Add(dgvr);

    Also you can investigate the example code here http://msdn2.microsoft.com/en-us/library/ddtce152.aspx.
    Thursday, February 21, 2008 11:36 AM

All replies

  • Hi,

    To resolve your problem you can try this

    Int32 columnNum = 1;
    DataGridViewRow dgvr = new System.Windows.Forms.DataGridViewRow();
    dgvr.CreateCells(dataGridView1);
    dgvr.Cells[columnNum].Value = "value1";
    dataGridView1.Rows.Add(dgvr);

    Also you can investigate the example code here http://msdn2.microsoft.com/en-us/library/ddtce152.aspx.
    Thursday, February 21, 2008 11:36 AM
  • Thanks, Mykhaylo!

     

    Thursday, February 21, 2008 1:39 PM
  • Thanks for the quick clean answer.
    Saturday, October 10, 2009 5:30 PM