Click here to Skip to main content
15,900,907 members
Please Sign up or sign in to vote.
4.80/5 (2 votes)
See more:
Dear Friends,

I need to add a data row in a dataset data table at a specified index. How to do that?.

I have a datatable filled with data in a dataset and i have to add a new row to this datatable in dataset(based on the some condition).

Thanks

Varun Sareen
Posted

private void InsertRow()
{
object[] objrow = new object[] {"Put your data what you want to insert
with same schema which you have for
your existing data table"};

for example:
object[] objrow = new object[] { "32", "Cipla", "Ram", DateTime.Now };



///My existing datatable name is "table"

DataRow row = table.NewRow(); ///creating new row in your datatable

row.ItemArray = objrow;///copying your data into data row object

table.Rows.InsertAt(row, 3);///insert row at 3rd index of datatable
}
 
Share this answer
 
Comments
Member 7744639 4-Jun-15 3:19am    
I have use one master Page user login wise access aspx files
C#
//Assuming this is the existing datatable you have
DataTable existingDataTable = GetMeDataFromSomeWhere();

//Add a new row to table
DataRow newRow = existingDataTable.NewRow();

newRow["ID"] = 999;
newRow["SomeColumn"] = "Manas Bhardwaj";

existingDataTable.Rows.Add(newRow);


There DataTable does not provide any interface to insert a row at certain position. But that can be done within a function where you can create a dataview [^]and sort the results as per your wish.
 
Share this answer
 
v2
Manas' basic approach works.

If you want to retain position in any relational data (either DataTable, or throught SQL), you must remember that tables are essentially order free. To get the effect you want, where items can have specific positions, I tend to work by adding an extra field (Index or Position) that can be used with an ORDER BY clause to get sorted results. In that case, inserting to the sorted data is equivalent to adding a row whose value for this extra field is between the values for the records above and below.

For DataTable objects, one of the Select method allows sorting the contents of the table. The following URL MSDN Article[^] shows how to do this - simply specify the filter condition as "TRUE" to not filter data.

Hope this helps
 
Share this answer
 
Comments
Member 12919915 27-Jul-18 14:10pm    
excellent solution thank you
Try
mDataSet.Tables(0).Rows.InsertAt(mDrow, myIndex)

Hope this helps.
 
Share this answer
 
Comments
CHill60 9-Oct-13 8:00am    
That's what Solution 3 suggested in December 2011 but with added comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900