How to dynamically add a row to Datagrid?

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.
 
G

Guest

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();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top