Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datatable select rows

Tags:

c#

I am using a datatable created by program. In this datatable i want to insert values in some specified columns.

Initially I am inserting primary key values leaving remaining columns null, when I am querying datatable with recently inserted value in Primary column to update same row, I am facing error Missing operand after ID operator

Can any one tell me the exact issue.

I am trying following code:

 dt.Rows.Add(1);
 int insertedValue = 1;
 DataRow[] dr = dt.Select("ID = '" + insertedValue.toString() + "'");

And the table structure after entring primary value is as follows.

ID    Volumn1    Volumn2    volumn3
--------------------------------------
1
like image 256
Pramod Avatar asked Nov 30 '22 15:11

Pramod


2 Answers

You can do this more cleanly with LINQ and make this a strongly typed operation.

Something like:

dt.Rows.Add(1);
int insertedValue = 1;
var result = 
        dt.AsEnumerable().Where( dr => dr.Field<int>( "ID" ) == insertedValue );

Working example:

DataTable dt = new DataTable();
dt.Columns.Add( "ID", typeof( int ) );
dt.Rows.Add( 1 );

var result = dt.AsEnumerable().Where( dr => dr.Field<int>( "ID" ) == 1 );
like image 181
Tim M. Avatar answered Dec 11 '22 09:12

Tim M.


You can simply format the selection string as shown below:

    DataRow[] dr = dt.Select(string.Format("ID ='{0}' ", insertedValue));

Feel free to let me know if this works for you.. Thanks

like image 39
Sunday Efeh Avatar answered Dec 11 '22 08:12

Sunday Efeh