So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader. Any fields that aren't in the reader would be left null on the resulting object. How do you test if a reader contains a specific field without just wrapping it in a try/catch?
This should do the trick:
Public Shared Function ReaderContainsColumn(ByVal reader As IDataReader, ByVal name As String) As Boolean
For i As Integer = 0 To reader.FieldCount - 1
If reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase) Then Return True
Next
Return False
End Function
or (in C#)
public static bool ReaderContainsColumn(IDataReader reader, string name)
{
for (int i = 0; i < reader.FieldCount; i++) {
if (reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) return true;
}
return false;
}
:o)
You can also use IDataReader.GetSchemaTable
to get a list of all the columns in the reader.
http://support.microsoft.com/kb/310107
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