Hi
I have below loop for datatable. I want to save each column value . Then i want to check if it doesn't have value 'S' or 'D' in it.
For .e.g
Col1 Col2 Col3
ND - B
- - D
Since D exists in second row it should exit out of loop
In first row neither S nor D exists so i a varaible value should be stored as 'not found'
Thanks

Amit MohantyRank #112 · 20K reputationPosted May 2, 2023, 5:21 AM EDT
Check the below example, this may help you.
using System; using System.Data; class Program { static void Main(string[] args) { // create sample data DataTable dt = new DataTable(); dt.Columns.Add("Col1", typeof(string)); dt.Columns.Add("Col2", typeof(string)); dt.Columns.Add("Col3", typeof(string)); dt.Rows.Add("ND", "-", "B"); dt.Rows.Add("-", "-", "D"); // loop through each column foreach (DataColumn col in dt.Columns) { bool found = false; // loop through each row of the column foreach (DataRow row in dt.Rows) { // get the value of the cell string cellValue = row[col].ToString(); // check if the value contains 'S' or 'D' if (cellValue.Contains("S") || cellValue.Contains("D")) { found = true; break; // exit the loop if 'S' or 'D' is found } } if (found) { Console.WriteLine($"{col.ColumnName} contains 'S' or 'D'"); break; // exit the loop if 'S' or 'D' is found in the column } else { Console.WriteLine($"{col.ColumnName} does not contain 'S' or 'D'"); } } } }Vishal JoshiRank #377 · 6.7K reputationPosted May 2, 2023, 6:26 AM EDT
Hello Ramco
Please try the below code to get the expected result.
// create datatable sample data DataTable dt = new DataTable(); dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Col1", typeof(string)); dt.Columns.Add("Col2", typeof(string)); dt.Columns.Add("Col3", typeof(string)); dt.Rows.Add(1, "ND", "-", "B"); dt.Rows.Add(2, "-", "-", "D"); DataTable responsedt = new DataTable(); responsedt.Columns.Add("Id", typeof(int)); responsedt.Columns.Add("Response", typeof(string)); // loop through datable rows foreach (DataRow row in dt.Rows) { bool isFound = false; foreach (DataColumn col in dt.Columns) { // get the value of the cell string cellValue = row[col].ToString(); // check if the value contains 'S' or 'D' if (!string.IsNullOrEmpty(cellValue) && (cellValue.Equals("S") || cellValue.Equals("D"))) { isFound = true; break; } } if (!isFound) { DataRow dataRow = responsedt.NewRow(); dataRow[0] = row[0]; dataRow[1] = "not found"; responsedt.Rows.Add(dataRow); } }Thanks
Vishal Joshi