Check if in a DataTable String / Record

I have a String and I need to check if any item_manuf_id column in the DataTable dtPs.Rows has a specific value

I can iterate over all the lines and compare

String id = dtPs.Rows[number]["item_manuf_id"].ToString() if ("some value".equals(id)) etc. 

but I am wondering if there is a way to check if a DataTable contains a record

+7
source share
4 answers

Something like that

  string find = "item_manuf_id = 'some value'"; DataRow[] foundRows = table.Select(find); 
+14
source

Use Find if item_manuf_id is the primary key:

 var result = dtPs.Rows.Find("some value"); 

If you only want to know if the value is, use the Contains method.

 if (dtPs.Rows.Contains("some value")) { ... } 

The primary key constraint also applies to Contains .

+4
source

You can loop over each row of the DataTable and check the value.

I use foreach loop when using IEnumerable s. Makes it very simple and clean to watch or process every line.

 DataTable dtPs = // ... initialize your DataTable foreach (DataRow dr in dtPs.Rows) { if (dr["item_manuf_id"].ToString() == "some value") { // do your deed } } 

Alternatively, you can use PrimaryKey for your DataTable . This helps in many ways, but you often need to define it before you can use it.

An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx

 DataTable workTable = new DataTable("Customers"); // set constraints on the primary key DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32)); workCol.AllowDBNull = false; workCol.Unique = true; workTable.Columns.Add("CustLName", typeof(String)); workTable.Columns.Add("CustFName", typeof(String)); workTable.Columns.Add("Purchases", typeof(Double)); // set primary key workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] }; 

After defining the primary key and filling in the data, you can use the Find (...) method to get the rows matching your primary key.

Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx

 DataRow drFound = dtPs.Rows.Find("some value"); if (drFound["item_manuf_id"].ToString() == "some value") { // do your deed } 

Finally, you can use the Select () method to find data in the DataTable , also found at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx .

 String sExpression = "item_manuf_id == 'some value'"; DataRow[] drFound; drFound = dtPs.Select(sExpression); foreach (DataRow dr in drFound) { // do you deed. Each record here was already found to match your criteria } 
+4
source

I think if your "item_manuf_id" is the primary key of a DataTable, you can use the Find method ...

 string s = "stringValue"; DataRow foundRow = dtPs.Rows.Find(s); if(foundRow != null) { //You have it ... } 
+1
source

All Articles