datatable - Table doesn't have primary key c# -


this question has answer here:

im trying delete rows datatable allitems rows datatables items; purpose of items datatable allitems not inside datatable items

all these rows fiiled same excel file contains several columns , equal.

i have tried using foreach loop:

foreach(datarow dr in allitems.rows) { if (items.contains(dr)) { allitems.rows.remove(dr); } 

but following error: table doesn't have primary key.

does knows how can delete these rows?

you have few choices here:

1. add primary key

you can add primary key data table when creating it.

assuming had column called "id" way:

allitems.primarykey = new datacolumn[] { worktable.columns["id"] };}  

or, cases primary key composite key (multiple columns):

allitems.primarykey = new datacolumn[] {                               worktable.columns["id"],                               worktable.columns["name"] };}  

this allow contains work correctly.

2. use dataview

you can use dataview filter out distinct rows;

dataview view = new dataview(allitems); datatable distinctvalues = view.totable(true, "column1", "column2" , ..., "columnn"); 

3. find matching rows using select

or can rely on select method test if corresponding row exists in items datatable based on statement that's sql whereclause:

list<datarow> rowstoremove = new list<datarow>();  foreach(datarow allitemrow in allitems.rows) {     if(items.select(string.format("id = {0}"),            allitemrow.field<int32>("id")).length == 0)     {         rowstoremove.add(allitemrow);     } }  rowstoremove.foreach(x => x.delete());  allitems.acceptchanges(); 

note it's important not remove rows while iterating collection of rows in allitems - instead, collect these rows, , remove them afterwards.

4. filter on way in

also note, , haven't tried it, but, depending on how selecting rows out of excel, may able use sql distinct clause; if using odbc load data excel try filtering @ source.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

keyboard - C++ GetAsyncKeyState alternative -

android - java.net.UnknownHostException(Unable to resolve host “URL”: No address associated with hostname) -