Thursday, March 22, 2012

oledbDataReader and null values

Hi,
I have a question about the data reader object in .Net. Is there an elegant way (ie without using lots of 'if' statements) to read a field in a database that is null?
The code I currently using is:
Dim objDataReader As oledbDataReader
'Database query code removed

If( objDataReader.IsDBNull(0) )Then myTextbox.Text = objDataReader.GetString(0)

I hate the fact that I have to use so many If statements. Is there a better way?
A similar question I have is dealing with parameterized queries and null values:
SQL = "Insert Into myTable (Name, Addr) Values (@dotnet.itags.org.Name, @dotnet.itags.org.Addr)"
objCmd.Parameters.Add(New OledbParameter("@dotnet.itags.org.Name", tbName.Text))
objCmd.Parameters.Add(NewOledbParameter("@dotnet.itags.org.Addr", tbAddr.Text))
If one of the parameters has no value the query throws an error. Is there a way to handle this.
ThanksAnyone?
Unfortunately I don't know of a better way but I normally solve this problem on the database side with string datatypes. For example in sql server I would use the isnull function - select isnull(astring, '') from mytable - which will return an empty string instead of a null. This is relevent where you will be assigning values to textboxes etc. If you are not using sql server then look maybe there is something similar to the isnul function.
As to paramaters and the example you give. Your database should accept an empty string as a paramater unless you have a setting on your table that does not allow empty strings. I don't see why it wouldnt work.

0 comments:

Post a Comment