Friday, May 21, 2021

How to : Check if a column exists in a datareader in C#

 Here is how we can do in  C# supported Frameworks!!

var fieldvalues = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();

//get column name here
if (fieldvalues.Contains("ErrorMessage"))
{
    errorMessge += Environment.NewLine + " ErrorMessage : " + reader["ErrorMessage"].ToString();
}
//get column name here
if (fieldvalues.Contains("ErrorProcedure"))
{
    errorMessge += Environment.NewLine + " ErrorProcedure : " + reader["ErrorProcedure"].ToString();
}

BTW, ErrorMessage will return the value after checking these fields 

Hope this helps 😀

No comments:

Post a Comment