How to dynamically add a row to Datagrid?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a datagrid that reads several rows of data from the database and loads
them on the screen.
Now I want to dynamically add a new row and assign the cells in the new row,
values.

When I try to create a datagridItem, I use the following call:
int newIndex = datagrid1.Items.Count; // returns 15 the current number of
rows in the grid
datagrid1.Items[newIndex].DataItem = new DataGridItem(newIndex, ?,
ListItemType.Item);

I get an error on the first parameter. It says that my index should not be
zero and be less than the collection count. (while I know that newIndex is
15) I don't know what to put for the 2nd parameter since I am not reading the
data for this row from database(datasource). I am pretty sure the third
parameter is correct.

After and if I can get this to work, how do I bind the new data to this row?

ANy help will be greatly appreciated.

Thanks
Any help is greatly appreciated.
 
Merdaad said:
I have a datagrid that reads several rows of data from the database and loads
them on the screen.
Now I want to dynamically add a new row and assign the cells in the new row,
values.

When I try to create a datagridItem, I use the following call:
int newIndex = datagrid1.Items.Count; // returns 15 the current number of
rows in the grid
datagrid1.Items[newIndex].DataItem = new DataGridItem(newIndex, ?,
ListItemType.Item);

I get an error on the first parameter. It says that my index should not be
zero and be less than the collection count. (while I know that newIndex is
15) I don't know what to put for the 2nd parameter since I am not reading the
data for this row from database(datasource). I am pretty sure the third
parameter is correct.

If you are reading the data for this row at the postback event from other
controls on the webform (e.g. TextBox, DropDownList) then you can create a
new row in the DataTable that you bound to the DataGrid then call again the
DataGrid.DataBind method. This would create the new DataGridItem for your
automatically.

DataRow myRow;
myRow = myDataTable.NewRow();
// put statements to assign the values to the dr.Items collection then add
it to the Table
myDataTable.Rows.Add(myRow);
//DataBind
MyDataGrid.DataSource = myDataTable;
MyDataGrid.DataBind();
 
Back
Top