How to check if a column exists in a datareader

I'm up against this problem for which I'm surprised to find no help.

I want to check if a column exists in the datareader before attempting to read it. If i don't check i get the indexOutofRange exception.

There is similar functionality with datatable where we do dt.Columns.IndexOf("ColName")

But how do we do this with datareader



Answer this question

How to check if a column exists in a datareader

  • Greenstrike

    Good question. I don't know why they didn't add a method to check for the existence of a column that did not throw an exception. I assume they have some good reason, but I never looked into it.

    Throwing and catching exceptions like that is a bad practice. I probably shouldn't have even mentioned it as I wouldn't put code like that into production, even though I see it all the time. I normally avoid the situation where I have to check for the existence of a column in a DataReader. Throwing exceptions does have performance penalties.

    If you can't avoid the check, GetSchemaTable looks to be the "best" option, even though the thought of a lookup table to determine the existence of a column seems overkill :)

    Regards,

    Dave



  • GoranP

    OK, this is what i ultimately settled for:

    I do a GetSchemaTable and the first column has all the "datareader column names".

    I do a loop ONCE and fill them into a SortedDictionary.

    Then I do a SortedDictionary.ContainsKey before accessing any column from the datareader.

    Works without any issues.

    Thanks Val, Dave


  • Duane Doutel

    This isn't a good programming practice since exceptions should be exceptional events and exceptions being thrown causes slower performance, but... :) you could just catch the exception and swallow it:

    try
    {
    object value = dr["ColumnName"];
    // Do something with the value...
    }
    catch(IndexOutOfRangeException e)
    {
    // Swallowed...
    }

    Regards,

    Dave



  • anru

    DataReader has method called GetSchemaTable that returns information about columns in a reader

  • GailG

    Dave,

    Believe it or not. I was doing the exact same thing when i saw your post. It's ugly alright, but gets the job done. But....do you think it might have performance issues My hunch is that it still is better than looping through all column names from GetSchemaTable. Also, do you think someone at MS just forgot to put that in or is it that darned difficult to do it.


  • Krivahn

    Actually looping will work much faster than catching an exception. With the good code design you need to loop only once at the beginning of the processing and prepare list of the columns.

  • How to check if a column exists in a datareader