开发者

How to add datarows to an already existing datatable?

开发者 https://www.devze.com 2023-03-31 08:41 出处:网络
I am having an datatable which is alread开发者_开发问答y populated. Now i want to add few rows to that datatable ,but some of rows might already exist in the datatable.I know its unneccesary but tht i

I am having an datatable which is alread开发者_开发问答y populated. Now i want to add few rows to that datatable ,but some of rows might already exist in the datatable.I know its unneccesary but tht is the requirement.

I tried couple of things and got "the row already exist in this table : & this row belongs to some other table" .I also tried importRow ,but i guess it avoid the duplicates by dafault.

Is there any way to do that .If the datatable has 7 rows and i want to add 3 more rows whether its already exist or not. My goal is to send 10 rows to the calling function .

Or is there any other approach altogether?

UPDATE

Using rowsToAdd.CopyToDataTable(dsCount.Tables[2], LoadOption.PreserveChanges); works but I'm not sure it's the proper way.


You can add new rows in DataTable using code below

DataRow newRow = dataTable.NewRow();
dataTable.Rows.Add(newRow);


To check for any duplicates try

if (table.Rows.Contain(PriKeyTypeValue)) /*See if a Primary Key Value is in 
the table already */
    continue;
else
    table.Row.Add(value1, value2, value3);

If you want to be able to insert duplicate rows but do not want to have an exception thrown set-up your primary key as a unique self-incrementing int then you can insert as many duplicates as you feel like without having to check to see if the table contains that value. Just make sure that it would suffice to have duplicates. There are plenty of examples of setting a primary key just search for it (msdn has at least one). Here is an example:

DataTable table = new DataTable();

table.Columns.Add("Column", typeof(int));

DataColumn column = table.Columns["Column"];
column.Unique = true;
column.AutoIncrement = true;
column.AutoIncrementStep = 1; //change these to whatever works for you
column.AutoIncrementSeed = 1;
table.PrimaryKey = new DataColumn[] { column };


Create a new row using the NewRow() function.

var dataTable = new DataTable();
var dataRow = dataTable.NewRow();

Then add your new row to your datatable

dataTable.Rows.Add(dataRow)


I believe you can use the NewRow() function of the DataTable if you're simply appending a row to the table.

DataTable table = new DataTable();    
DataRow row = table.NewRow();

table.Rows.Add(row);

Will that not suffice?


The most straightforward method. After spending a few hours trying everything else.

DataRow dr = ds.Tables[0].NewRow();
dr["ColumnName1"] = "columnvalue"; //string
dr["ColumnName2"] = 123 //int
ds.Tables[0].Rows.Add(dr);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号