Kate
Kate

Reputation: 372

Check if value exist in datatable

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?

Upvotes: 1

Views: 18225

Answers (2)

mehmet mecek
mehmet mecek

Reputation: 2685

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));

Upvotes: 1

Thilina H
Thilina H

Reputation: 5804

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")
         {
         }      
     }

Upvotes: 1

Related Questions