Checking for DBNull

Posted by Jim Lahman on Geeks with Blogs See other posts from Geeks with Blogs or by Jim Lahman
Published on Fri, 04 Mar 2011 17:46:23 GMT Indexed on 2011/03/04 23:25 UTC
Read the original article Hit count: 261

Filed under:

Using a table adapter to a SQL Server database table that returns a NULL record.  We determine the fields are NULL by comparing against System.DBNull

Looking the NULL records in SQL Management studio

 

Using a table adapter to retrieve a record

 

   1:  try
   2:  {
   3:      this.vTrackingTableAdapter.FillByTrkZone(this.dsL1Write.vTracking, iTrkZone);
   4:  }
   5:  catch (Exception ex)
   6:  {
   7:       sLogMessage =  String
   8:               .Format("Error getting coil number from tracking table at {0} - {1}",
   9:                              sTrkName,
  10:                              ex.Message);
  11:       throw new CannotReadTrackingTableException(sLogMessage);
  12:  }

 

Looking at the record as it returned from the table adapter:

 

ItemArrayObject Column
[0] ChargeCoilNumber
[1] HeadWeldZone
[2] TailWeldZone
[3] ZoneLen
[4] ZoneCoilLen
[5] Confirmed
[6] Validated
[7] EntryWidth
[8] EntryThickness

 

Since each item in the ItemArray is an object, we can test for null

 

   1:  if (dsL1Write.vTracking.Rows[0].ItemArray[0] == System.DBNull.Value)
   2:  {
   3:        throw new NoCoilAtPORException("NULL coil found at tracking zone " + sTrkName);
   4:  }

 

If no records were returned by the table adapter

   1:  if (dsL1Write.vTracking.Rows.Count == 0)             
   2:  {                                                    
   3:      throw new NoCoilAtPORException("No coils found at tracking zone " + sTrkName);
   4:  }

© Geeks with Blogs or respective owner