473,657 Members | 2,414 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DBNull after read, need to cast

Hi,

I have a question. I have a stored procedure that can give a value
like a string or an int. But in some cases it can be DBNull. What is
the standard way to handle this?
- I can create a storedprocedure that always give the 0 value of the
type.
- Create an if statement around every assignment.

Maybe someone else have an idea?

Patrick

Mar 5 '07 #1
9 2630
On 5 mrt, 17:12, patrick.san...@ gmail.com wrote:
Hi,

I have a question. I have a stored procedure that can give a value
like a string or an int. But in some cases it can be DBNull. What is
the standard way to handle this?
- I can create a storedprocedure that always give the 0 value of the
type.
- Create an if statement around every assignment.

Maybe someone else have an idea?

Patrick
At this moment I have this code
if (rdr["MatchBwDepotNr "].GetType() !=
typeof(System.D BNull) )
{
Input.BwplDepot Nr =
Convert.ToInt32 (rdr["MatchBwDepotNr "]); ;
}
And I think it is quite big if you have to do it for every record....
I hope there is a quicker way to do it.

Mar 5 '07 #2
On 5 Mar, 16:18, patrick.san...@ gmail.com wrote:
On 5 mrt, 17:12, patrick.san...@ gmail.com wrote:
Hi,
I have a question. I have a stored procedure that can give a value
like a string or an int. But in some cases it can be DBNull. What is
the standard way to handle this?
- I can create a storedprocedure that always give the 0 value of the
type.
- Create an if statement around every assignment.
Maybe someone else have an idea?
Patrick

At this moment I have this code
if (rdr["MatchBwDepotNr "].GetType() !=
typeof(System.D BNull) )
{
Input.BwplDepot Nr =
Convert.ToInt32 (rdr["MatchBwDepotNr "]); ;
}
And I think it is quite big if you have to do it for every record....
I hope there is a quicker way to do it.
if(DBNull.Value == rdr["MatchBwDepotNr "])
{
//we are null
}

should do it.

And if you know the column ordinal rdr.IsDBNull(co lumn number) works
too, but who wants to work with ordinals.

framework 2 might allow rdr["MatchBwDepotNr "].IsDBNull, but I i don't
have it on this PC so I can't check.

Mar 5 '07 #3
DeveloperX <nn*****@operam ail.comwrote:
And I think it is quite big if you have to do it for every record....
I hope there is a quicker way to do it.

if(DBNull.Value == rdr["MatchBwDepotNr "])
Or:

if (rdr["MatchBwDepotNr "] is DBNull)

which I think is the neatest version.

(Note that the whole constant==varia ble idiom isn't required in C#, as
only boolean expressions are valid for "if" statements. Even if I were
to use ==, I'd suggest reversing the operands from your code, to make
it easier to read.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 5 '07 #4
On Mar 5, 2:34 pm, Jon Skeet [C# MVP] <s...@pobox.com wrote:
Even if I were
to use ==, I'd suggest reversing the operands from your code, to make
it easier to read.)
You don't subscribe to the catch-inadvertent-assignment-typos-at-
compile-time methodology then, I take it?

cdj

Mar 6 '07 #5
Jon Skeet [C# MVP] wrote:
DeveloperX <nn*****@operam ail.comwrote:
>>And I think it is quite big if you have to do it for every record....
I hope there is a quicker way to do it.
if(DBNull.Valu e == rdr["MatchBwDepotNr "])

Or:

if (rdr["MatchBwDepotNr "] is DBNull)

which I think is the neatest version.
if(rdr.IsDBNull (ColNoMatchBwDe potNr))

would be my preferred way if column number is an option.

Arne
Mar 6 '07 #6
sherifffruitfly <sh************ *@gmail.comwrot e:
On Mar 5, 2:34 pm, Jon Skeet [C# MVP] <s...@pobox.com wrote:
Even if I were
to use ==, I'd suggest reversing the operands from your code, to make
it easier to read.)

You don't subscribe to the catch-inadvertent-assignment-typos-at-
compile-time methodology then, I take it?
Try reversing the operands - it won't compile. C# doesn't have the same
problem as C, because if (foo) will only compile if the type of "foo"
is boolean.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 6 '07 #7
On 6 Mar, 07:13, Jon Skeet [C# MVP] <s...@pobox.com wrote:
sherifffruitfly <sherifffruit.. .@gmail.comwrot e:
On Mar 5, 2:34 pm, Jon Skeet [C# MVP] <s...@pobox.com wrote:
Even if I were
to use ==, I'd suggest reversing the operands from your code, to make
it easier to read.)
You don't subscribe to the catch-inadvertent-assignment-typos-at-
compile-time methodology then, I take it?

Try reversing the operands - it won't compile. C# doesn't have the same
problem as C, because if (foo) will only compile if the type of "foo"
is boolean.

--
Jon Skeet - <s...@pobox.com >http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
It's force of habit and it does stop me doing if (b = true) :)

Google groups seems to be playing up, so this is the only post I can
read in this thread at the moment, apologies if I've missed something.

Mar 6 '07 #8
On Mar 6, 1:15 pm, "DeveloperX " <nntp...@operam ail.comwrote:
It's force of habit and it does stop me doing if (b = true) :)
How often do you write that rather than if (b) anyway? I can't
remember the last time I did - and I don't think I've *ever*
accidentally written if (b=true).

To me, it feels obvious that

if (x==5)
is easier to read than
if (5==x)

- it's a more natural way of thinking about things. I would always
say, "Is your name Peter?" rather than "Is Peter your name?" for
instance.

Just because C/C++ is broken enough to make it worth bending
readability for safety doesn't mean it's worth preserving that habit
in saner languages :)
Google groups seems to be playing up, so this is the only post I can
read in this thread at the moment, apologies if I've missed something.
Nah, not a lot :)

Jon

Mar 6 '07 #9
On 6 Mar, 13:50, "Jon Skeet [C# MVP]" <s...@pobox.com wrote:
On Mar 6, 1:15 pm, "DeveloperX " <nntp...@operam ail.comwrote:
It's force of habit and it does stop me doing if (b = true) :)

How often do you write that rather than if (b) anyway? I can't
remember the last time I did - and I don't think I've *ever*
accidentally written if (b=true).

To me, it feels obvious that

if (x==5)
is easier to read than
if (5==x)

- it's a more natural way of thinking about things. I would always
say, "Is your name Peter?" rather than "Is Peter your name?" for
instance.

Just because C/C++ is broken enough to make it worth bending
readability for safety doesn't mean it's worth preserving that habit
in saner languages :)
Google groups seems to be playing up, so this is the only post I can
read in this thread at the moment, apologies if I've missed something.

Nah, not a lot :)

Jon
Perfectly reasonable point, I would do if(b) too. Well I'll try and
break the habit, but it's been a long time, what's the betting the
first time I do I introduce a fatal bug :)

Mar 6 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
3597
by: jim | last post by:
This line of code returns error 13, cast from 'DBNull' to type 'String' is not valid If IsDBNull(Clinics.Clinics.Item(A).Workphone) The <other code End I Clinics.Clinics is a dataset that was loaded using a left join from two MS SQL database tables. The workphone element is null because there was no corresponding record from the right side of the join The generated code for retrieving the value of 'Workphone' as a dataset property...
5
7460
by: DraguVaso | last post by:
Hi, Something I don't understand about a Typed DataSet: When a value in the DataSet is DBNull, it throws this error: "Cannot get value because it is DBNull". But aren't Typed DataSets invented to make life easier, to be able to get to tge Tables and Values with less code, in less time? But with this thing you need to add a Try-Catch around every statement when using the value, add for each value a default value in your DataSet (and...
2
1494
by: Filipe Cristóvão | last post by:
Hi, I know that this is a newbie's question, but I need to know how i do to know if a field in a table is DBNull. If I try to write (with response.write) the field, it gives me an error: "Cast from type 'DBNull' to type 'String' is not valid". Thanks for any help. -- Filipe Cristóvão
6
5430
by: tshad | last post by:
The error I am getting is: ******************************************************************* Exception Details: System.InvalidCastException: Cast from type 'DBNull' to type 'String' is not valid. Source Error: Line 144: firstName.text = ClientReader("firstName") Line 145: lastName.text = ClientReader("lastName")
4
14920
by: Dursun | last post by:
Hi, I am trying to assign NULL to a datetime field in the SQL Server database. Here is the code that does NOT work: INSERT INTO ... .... VALUES ... .... CType(IIf(dateWitness2Date.Checked, dateWitness2Date.Value, DBNull.Value), DateTime), & ...
8
17513
by: MattB | last post by:
Hello. I have a vb.net (asp.net) application that uses ado.net datasets. At one point, I need to check a text field in a DataTable to see if there's any text in it before performing text operations on that record. I thought I could just test using something like this: If Not IsNothing(e.Item.DataItem("guest_name")) Then .... End If But it seems a value of DBNull passes this test and evaluates as not
8
3338
by: wink martindale | last post by:
Hello, I am writing a vb.net app.Using MySql db with the corelabs connector. I am getting the following error when attempting to read values from a datareader: Cast from type 'DBNull' to type 'String' is not valid. This error occurs on a field that DOES have data in it, but I can't figure out why! Here is a sample of the code I am using:
2
2934
by: Julian | last post by:
I have the following code: Dim strQuery As String = "SELECT tblData.CoPayFundGrant, tblData.M_DSS_SSA_Benefits, tblData.O_DSS_SSA_Benefits, " & _ "tblData.Ref_MPS, tblData.Ref_LA, tblData.Ref_DCMH, tblData.Place_Comm, tblData.Rem_Comm, tblData.Core_Case_Man, tblData.Ref_DCMH_Case_Man " & _ "FROM tblData;" Dim rsDataManip As ADODB.Recordset = cnnJET.Execute(strQuery) With rsDataManip
4
35307
by: Jose Fernandez | last post by:
Hello. how can i cast a null value from a datareader (System.DBNull) to dateTime I have an object. One of its fields is a DateTime type field. From the database i am getting System.DBNull values from its corresponding column. What can I do to cast it? i don't want to implement a custom method for this. myClass.ExpirationDate=Convert.ToDateTime(dr); // throw an exception.
0
8402
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8315
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8829
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8734
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8508
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6172
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5633
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4323
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2733
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.