Adding Multiple Rows to Dynamically Created datatable

Posted by Raj.Trivedi under Windows Forms on 3/8/2015 | Points: 10 | Views : 15610 | Status : [Member] [MVP] | Replies : 1
Hello Team,

I have created a data table dynamically and added dynamic columns and created a row and i have added the row to datatable.The same data table i have binded to gridview.
Now when i am adding a second new row to dynamically created data table the previous row does not remain in the data table and the gridview gets bind with the new row added.
Basically i want store all dynamically created rows in the dynamically created data table.

I am pasting the code i have tried.

private void btnAdd_Click(object sender, EventArgs e)
DataTable dttableforGrid = new DataTable();
// Generating new DataColumn for Datatable
DataColumn col1 = new DataColumn("InvoiceNo");
DataColumn col2 = new DataColumn("ProductId");
DataColumn col3 = new DataColumn("ProductCode");

// Setting data type to column
col1.DataType = System.Type.GetType("System.String");
col2.DataType = System.Type.GetType("System.Int16");
col3.DataType = System.Type.GetType("System.String");


// Adding row to data table
DataRow row = dttableforGrid.NewRow();
row[col1] = txtInvoice.Text.Trim();
row[col2] = GlobalProductId;
row[col3] = GlobalProductCode;

// Adding row to data table
int Snu = 0;
// binding row to data gridview
if(dttableforGrid.Rows.Count >0)
foreach (DataRow rows in dttableforGrid.Rows)

xgDetail.Rows[Snu].Cells[0].Value = Convert.ToString(rows["InvoiceNo"]);
xgDetail.Rows[Snu].Cells[1].Value = Convert.ToString(rows["ProductId"]);
xgDetail.Rows[Snu].Cells[2].Value = Convert.ToString(rows["ProductCode"]);


I am not able to store previously added rows to data table it only stores new rows that gets generated on ADD button click. The previous rows are deleted from data table. Need all dynamic rows to be stored in data table generated on ADD button click

"Sharing is Caring"
Please mark as answer if your Query is resolved


Posted by: Bandi on: 3/9/2015 [Member] [MVP] Platinum | Points: 25


Mark This Response as Answer

Raj.Trivedi, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response