Glllek
Glllek

Reputation: 13

check if datatable contains certain value

I tried to check, if my datatable created before from sql select contains number equal to my NumericUpDown. 'table' was created by sqldatareader with Fill

var table = new DataTable();
var da = new SqlDataAdapter("select id from table3 where typ in (0,1)", connectionString);
                
da.Fill(table);

Table is very simple:

id
2
3
5

what i tried (nudNrArk is my numericUpDown):

if (table.AsEnumerable().Any(s => s.Equals(nudNrArk.Value)))

if (table.AsEnumerable().Where(c => c.Field<int>("id").Equals(nudNrArk.Value)).Count() > 0)

those both never return true

if (table.Rows.Contains(nudNrArk.Value)) this (looks as simplest way) want a primary key

Is there a simple way to add primary key to column in this table? Or better way to check this?

Upvotes: 0

Views: 466

Answers (1)

TJacken
TJacken

Reputation: 369

First of all this is low explained question it is not clear what you want.

This should be work:

   if (table.AsEnumerable().Where(c => c.Field<int>("id").Equals(nudNrArk.Value)).Count() > 0)

So question is what is nudNrArk.Value is property Value type int, string or object? Try with this:

 if (table.AsEnumerable().Where(c => c.Field<int>("id") == (int)nudNrArk.Value).Count() > 0)

Equals won't work if they are not same type, if you want to compare two objects you should override Equals method of class and write your own method for Equals.

Edit:

This is way to add primary key on datatable:

table.PrimaryKey = new DataColumn[] { table.Columns["id"]};

Upvotes: 1

Related Questions