0

How to add rows into a datatable dynamically?

I created some columns with this code:

DataTable obj_dt_grdvw = new DataTable();
obj_dt_grdvw.Columns.Add("_Pur_Product_Id", typeof(string));
obj_dt_grdvw.Columns.Add("Product_pur_Name", typeof(string));

Now I tried to add a row of data but showing error "there is no row at 0"

obj_dt_grdvw.Rows[0]["_Pur_Product_Id"] ="12";
obj_dt_grdvw.Rows[0]["Product_pur_Name"] ="milk";

What is my mistake?

1 Answer 1

3

When you create new datatable, it is empty - i.e. there is no rows. That's why you can't find row at index 0. You should create and add rows manually.

Use DataTable.NewRow method to create new row with same columns (i.e. same schema) as your datatable:

DataRow row = obj_dt_grdvw.NewRow(); // create new row
row["_Pur_Product_Id"] ="12"; // set field values
row["Product_pur_Name"] ="milk";
obj_dt_grdvw.Rows.Add(row); // add this new row to table rows
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.