Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cast exception when retrieve null from db? 1

Status
Not open for further replies.

Tokhra

Programmer
Oct 1, 2003
134
ES
Hi all,

When retrieving data from the database I use the following method:


owner.Fax = (string) data["Fax"];

(where data is a SqlDataReader)

However, if data["Fax"] is null, it generates a Cast Exception, id rather not have to put if statements all over each retrieval. So whats the "standard" way of achieving this?

I guess I could put a try { } catch() around it to silence the exception, but would it then not move onto the next statement?

e.g.

try
{

wner.OwnerID = (int) data["OwnerID"];
owner.Title = (string) data["Title"];
owner.Forename = (string) data["Forename"];
owner.Surname = (string) data["Surname"];
owner.Telephone = (string) data["Telephone"];
}
catch(SomeException ex) { // do nothing }

I also thought about putting the null handling in the properties of the owner class, but that would mean each property would have to be of type object would it not?

Id appreciate anyones advice on this,

Thanks,
Matt.
 
If you use
Code:
owner.Fax = data["Fax"].ToString();
then the ToString method will take care of any null values. The other way to check for nulls (although it is more long winded) is:
Code:
if (data.IsDBNull(data.GetOrdinal("Fax")))

    textBox1.Text = "";

else
					
    textBox1.Text = (string)sdr["Fax"];
 
Oops, obviously the last line should read:

textBox1.Text = (string)data["Fax"];
 
Ah ok, the ToString() method looks nice and easy :)

Thanks very much.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top