8
votes

I have a DataTable i am trying to do a simple select row that contains a value.

My code

  var LoginDetails = from myRow in DTOperators.AsEnumerable()
                           where myRow.Field<string>(0) == UserName
                           select myRow;

I am trying to check if the string UserName exists at position 0 the rows in the datatable

When i run this query i get a blank datarow back.

I have tried to use [] around the position that i want to select.

anyone able to see what i am doing wrong.

1
looks good, what is the exception or problem? - Matten
Is the field index correct? I understand you want to check at position 0 but does it contains the names? I tried with a simple datatable and I checked on position 1 and it did return me 2 records. - Nilesh
You're checking == Even spaces may cause trouble here! - Sriram Sakthivel
By blank, do you mean one DataRow with null & default values for all of the fields? - Keith Payne

1 Answers

23
votes

you have to check if you comparing with right column and check data in your table. this work fine:

var DTOperators = new DataTable();
var UserName = "test";
DTOperators.Columns.Add("UserName", typeof(string));
DTOperators.Rows.Add("test1");
DTOperators.Rows.Add("test");
var LoginDetails = from myRow in DTOperators.AsEnumerable()
                     where myRow.Field<string>(0) == UserName
                     select myRow;

I've got Enumerable with one datarow. You also could try to get data by columnName:

var LoginDetails = DTOperators.Rows
                              .Cast<DataRow>()
                              .Where(x => x["UserName"] == UserName).ToList();