1

i have sql command and I save values into datatable.

con.Open();
cmd0.CommandText = "Select ......";
DataTable dtbl = new DataTable();
dtbl.Load(cmd0.ExecuteReader());

And i have value String Name. I need to know, if the value in String Name is in the datatable dtbl...It is possible?

helb
  • 7,609
  • 8
  • 36
  • 58
Kate
  • 372
  • 2
  • 11
  • 24

2 Answers2

1

Since there's only a single value returned, you could do this:

string value = (string)command.ExecuteScalar();

Anyway the DataTable has a collection .Rows of DataRow elements.Each DataRow corresponds to a record row in your database.

If you want to access a single value, do something like this:

   foreach(DataRow row in dtbl.Rows)
     { 
         if(row["ColumnName"].ToString()=="Name")
         {
         }      
     }
Thilina H
  • 5,754
  • 6
  • 26
  • 56
1

Yes it is possible, you can use DataTable.Compute method like as follows.

string valueToSearch = "lorem";
string columnName = "Name";
int count =
    (int) dtbl.Compute(string.Format("count({0})", columnName),
        string.Format("{0} like '{1}'", columnName, valueToSearch));
mehmet mecek
  • 2,615
  • 2
  • 21
  • 25
  • Now i have this error: Syntax Error: Before the LIKE operator is missing operand. – Kate Nov 13 '13 at 09:05
  • You can use `=` instead of `like`. where clause should be written here just like in a SQL sentence (`select count(Name) from dtbl where Name like 'yourName'`). Additionally the answer above, that loops in dtbl.Rows and checks the equality, is costful, dtbl.Compute method already does what you needed. – mehmet mecek Nov 13 '13 at 09:57