user1523935
user1523935

Reputation: 87

How to handle Column '<ColumnName>' does not belong to table

i have a scenario where some column name of a DataTable may not be present. 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 whether this DataTable contains a column called Address or not. Is it possible like we have in Dictionary like:

if (objDictionary.ContainsKey("Address"))
 {
 }

Upvotes: 6

Views: 18940

Answers (1)

Habib
Habib

Reputation: 223187

You can use DataColumnCollection.Contains Method method as

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

DataColumnCollection.Contains Method

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

Upvotes: 12

Related Questions