3

I have code that looks like:

  //System.Data.IDataRecord dr
  try
  {
       Consolidated = Utility.NullConvert.ToBool(dr[Constants.Data.Columns.cConsolidated], false);
  }
  catch (IndexOutOfRangeException) { } //swallow

I don't know if the consolidated column will be present in the datareader, so I do that to check. It works fine (is a little hackish, though).

When I attach a debugger though, it breaks on that whenever it throws the exception however. Extremely annoying.

Is there a better way to write that code; or is there some Visual Studio way of telling it to ignore the exception and not break (but only right here; not everywhere).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom Ritter
  • 99,986
  • 30
  • 138
  • 174

3 Answers3

2

Yes, you can use the GetSchemaTable() method of the datareader to get a list of columns, then you can see if that column exists.

You might find this very similar question helpful.

Community
  • 1
  • 1
Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173
  • I had to cast the interface; but this worked well. I couldn't use GetOrdinal as this threw the same exception I was trying to avoid. – Tom Ritter Dec 31 '08 at 17:54
  • SchemaTable is not the table the DataReader refers to , over 8 years has passed but this page still pop up in Google when asking this question. – James Roeiter Aug 15 '16 at 17:15
2

I would simply use GetOrdinal() at the start of the loop to find the column indexes first (and store in a variable). Then just check whether it is >=0. This has the advantage of improving performance too (as long as you then use this integer for all access, not the name).

And no, there is no elegant way of ignoring a particular exception. You could catch and swallow, but that is not a good approach.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
-1

You can simply use the following code:

reader.GetSchemaTable().Columns.Contains("Your_Column")

This will return a boolean.

If reader.GetSchemaTable().Columns.Contains("ContactID") Then
   ' Do something
End If
Chad
  • 1,531
  • 3
  • 20
  • 46
Kevin Dark
  • 458
  • 5
  • 15