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; } }
You can use the DataColumnCollection of Your datatable to check if the column is in the collection.
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.
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.
You can simply check like this:
return row.Table.Columns.Contains(columnName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With