Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ADO.NET DataRow - check for column existence

How do I check for the existence of a column in a datarow?

I'm building datatables to organize some data that I've already pulled back from the database. Depending on the type of data in each row, I need to create a datatable with different columns. Then, later on, I want to check and see if the datatable I am looking at has a certain column.

I know I can catch the exception and handle it that way, but I'm curious if there is a property or method on the datarow object that will do this for me?

Here's how I can do it by catching the exception:

public static String CheckEmptyDataRowItem(DataRow row, String rowName, String nullValue) {     try     {         return row[rowName].ToString();     }     catch (System.ArgumentException)     {         return nullValue;     } } 
like image 475
Tone Avatar asked Jun 09 '09 15:06

Tone


People also ask

How do I check if a DataRow column exists?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

How do you DataRow in C#?

To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition.

How do I add data to DataRow?

After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method.


1 Answers

You can simply check like this:

return row.Table.Columns.Contains(columnName); 
like image 152
Gaurav Avatar answered Sep 22 '22 22:09

Gaurav