ADO.NET DataRow - check for column existence

雨燕双飞 提交于 2019-12-03 18:28:24

问题


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;
    }
}

回答1:


You can simply check like this:

return row.Table.Columns.Contains(columnName);



回答2:


DataTables have that schema info, so check if the Row's Table's Columns collection contains the field.



来源:https://stackoverflow.com/questions/970985/ado-net-datarow-check-for-column-existence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!