During development I encountered this problem. So here I am posting a solution for the same.
Suppose a reader is reading result set which normally returns fields ‘A’ ‘ B’ AND ‘C’ and in some cases it also returns ‘W’.So your dataread method is likeLet’s have some object for the data to persist.
PublicObjectDemoObject{//string Property A//string Property B//string Property C//string Property W//ConstructorObject(stringa,stringb,stringc){A=a;B=b;C=c;W=string.Empty;}Object(stringa,stringb,stringc,stringw){A=a;B=b;C=c;W=w;}}privateDemoObjectDataRead(SqlDataReaderreader){//Some Code//returnsobjectasObject}privateObjectDataRead(SqlDataReaderreader){//Some Code//if(reader["A"]!=null)stringa=reader.GetString(“A”);if(reader["A"]!=null)stringb=reader.GetString(“B”);if(reader["A"]!=null)stringc=reader.GetString(“C”);//Following line of code throws IndexOutOfRangeExceptionif(reader["W"]!=null)stringw=reader.GetString(“W”);//Some Code//……returnsnewDemoObject(a,b,c,w);}
It has the GetOrdinal() method as well, but it throws an exception if the reader doesn’t contain the field
So the solution is to use GetSchemaTable. It returns a table holding the schema of the reader. There is one row in the table for each column returned in the reader, and the columns of the schema table define properties of the reader’s result set, such as the column name, size, data type and so on. We need to filter the rows in that table to just the row matching the column we want, theschema table holds 1 row per column. The easiest way to do this is with the default view. e.g. if I were looking for a row called “myrow” in a reader’s results, I could do this
//Create a method which verifies if a column exists in a particular row being read by datareaderprivateboolColumnExists(SqlDataReaderreader,stringcolumnName){reader.GetSchemaTable().DefaultView.RowFilter=“ColumnName=‘”+columnName+“‘”;return(reader.GetSchemaTable().DefaultView.Count>0);}SonowReadDatamethodwilllooklikeprivateObjectDataRead(SqlDataReaderreader){//Some Code//if(reader["A"]!=null)stringa=reader.GetString(“A”);if(reader["A"]!=null)stringb=reader.GetString(“B”);if(reader["A"]!=null)stringc=reader.GetString(“C”);//Check only those columns where you have doubtsif(ColumnExists(reader,“W”)){if(reader["W"]!=null)stringw=reader.GetString(“W”);}//Some Code//……returnsnewDemoObject(a,b,c,w);}