How to handle <ColumnName> 'columns does not apply to a table

I have a scenario where some column DataTable name may be missing. Because I am creating a dynamic DataTable .

 DataTable tbl = new DataTable(); tbl.Columns.Add("Roll"); tbl.Columns.Add("Name"); DataRow dr = tbl.NewRow(); dr["Name"] = "Arshad"; dr["Roll"] = 1; tbl.Rows.Add(dr); Console.WriteLine(dr["Address"]);// exception, or Console.WriteLine(Convert.ToString(dr["Address"])); 

I want to check if this DataTable column contains an address or not. Is this possible as in Dictionary , for example:

 if (objDictionary.ContainsKey("Address")) { } 
+6
source share
1 answer

You can use the DataColumnCollection.Contains Method as

 if(dt.Columns.Contains("Address")) //column exists 

Method DataColumnCollection.Contains

Checks if the collection contains a column with the specified name.

+10
source

All Articles