Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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"))
 {
 }
like image 757
user1523935 Avatar asked Apr 04 '13 07:04

user1523935


People also ask

How do you handle column does not belong to table in C#?

Solution 1Add(new DataColumn("@Id", typeof(int))); DataRow dr = dt. NewRow(); dr["Id"] = 666; You will get the same error. DataTable dt = new DataTable(); dt.

Which does not belong to create a table in HTML?

So Table, tr, td belongs to table tags in HTML and form does not belong.


1 Answers

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.

like image 68
Habib Avatar answered Nov 15 '22 00:11

Habib