473,626 Members | 3,231 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Don't Understand Error Message (Database)

The following code raises the error "Specified cast is not valid."

MembershipUser user = Membership.GetU ser(userId);
DataSet ds = DataLayer.ExecQ ueryData("SELEC T * FROM mc_Clients WHERE
UserId='" + userId.ToString () + "'");
if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
return null;
ClientEx client = new ClientEx();
client.ClientDa ta = new Client();
client.ClientDa ta.Email = user.UserName;
client.ClientDa ta.UserID = user.ProviderUs erKey;
client.ClientDa ta.LastLogin = user.LastLoginD ate;
DataRow dr = ds.Tables[0].Rows[0];

// ...

if (!Convert.IsDBN ull(dr["Sex"]))
client.Sex = (int)dr["Sex"]; <<== ERROR HERE!

// ...

In the database table, Sex has a data type=smallint and nullable=True, and
client.Sex has a data type of int.

If I attempt to examine the contents of dr["Sex"] in the debugger, it shows
a value of 0x0000. If I attempt to examine the contents of (int)dr["Sex"] in
the debugger, it shows an error about not being able to unbox (sorry I no
longer have the exact text).

Any suggestions?

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Jan 11 '08 #1
38 2021
"Jonathan Wood" <jw***@softcirc uits.comwrote in message
news:%2******** **********@TK2M SFTNGP04.phx.gb l...
The following code raises the error "Specified cast is not valid."
Yes, it would do...
if (!Convert.IsDBN ull(dr["Sex"]))
if (dr["Sex"] != DBNull.Value)
In the database table, Sex has a data type=smallint
So the Sex field can have a range of values from -32,768 to 32,767...?
http://msdn2.microsoft.com/en-us/lib...8(SQL.80).aspx
--
Mark Rae
ASP.NET MVP
http://www.markrae.net

Jan 11 '08 #2
What type is client.Sex? Looks like whatever it is, it cannot accept int as a
value. Unless the Convert of the (int)dr["Sex"] is failing because it
itself is not an integer.

-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
MetaFinder: http://www.blogmetafinder.com
"Jonathan Wood" wrote:
The following code raises the error "Specified cast is not valid."

MembershipUser user = Membership.GetU ser(userId);
DataSet ds = DataLayer.ExecQ ueryData("SELEC T * FROM mc_Clients WHERE
UserId='" + userId.ToString () + "'");
if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
return null;
ClientEx client = new ClientEx();
client.ClientDa ta = new Client();
client.ClientDa ta.Email = user.UserName;
client.ClientDa ta.UserID = user.ProviderUs erKey;
client.ClientDa ta.LastLogin = user.LastLoginD ate;
DataRow dr = ds.Tables[0].Rows[0];

// ...

if (!Convert.IsDBN ull(dr["Sex"]))
client.Sex = (int)dr["Sex"]; <<== ERROR HERE!

// ...

In the database table, Sex has a data type=smallint and nullable=True, and
client.Sex has a data type of int.

If I attempt to examine the contents of dr["Sex"] in the debugger, it shows
a value of 0x0000. If I attempt to examine the contents of (int)dr["Sex"] in
the debugger, it shows an error about not being able to unbox (sorry I no
longer have the exact text).

Any suggestions?

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Jan 11 '08 #3
As stated, client.Sex is an int.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

"Peter Bromberg [C# MVP]" <pb*******@yaho o.NoSpamMaam.co mwrote in message
news:23******** *************** ***********@mic rosoft.com...
What type is client.Sex? Looks like whatever it is, it cannot accept int
as a
value. Unless the Convert of the (int)dr["Sex"] is failing because it
itself is not an integer.

-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
MetaFinder: http://www.blogmetafinder.com
"Jonathan Wood" wrote:
>The following code raises the error "Specified cast is not valid."

MembershipUser user = Membership.GetU ser(userId);
DataSet ds = DataLayer.ExecQ ueryData("SELEC T * FROM mc_Clients WHERE
UserId='" + userId.ToString () + "'");
if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count ==
0)
return null;
ClientEx client = new ClientEx();
client.ClientDa ta = new Client();
client.ClientDa ta.Email = user.UserName;
client.ClientDa ta.UserID = user.ProviderUs erKey;
client.ClientDa ta.LastLogin = user.LastLoginD ate;
DataRow dr = ds.Tables[0].Rows[0];

// ...

if (!Convert.IsDBN ull(dr["Sex"]))
client.Sex = (int)dr["Sex"]; <<== ERROR HERE!

// ...

In the database table, Sex has a data type=smallint and nullable=True,
and
client.Sex has a data type of int.

If I attempt to examine the contents of dr["Sex"] in the debugger, it
shows
a value of 0x0000. If I attempt to examine the contents of (int)dr["Sex"]
in
the debugger, it shows an error about not being able to unbox (sorry I no
longer have the exact text).

Any suggestions?

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Jan 11 '08 #4
Mark,
>The following code raises the error "Specified cast is not valid."

Yes, it would do...
> if (!Convert.IsDBN ull(dr["Sex"]))

if (dr["Sex"] != DBNull.Value)
So what does that mean? Does that mean dr["Sex"] was, in fact, null but my
check was wrong? And what the heck does Convert.IsDBNul l() do? This seemed
to work on some other fields.

Actually, I just tried this:

if (dr["Sex"] != DBNull.Value)
client.Sex = (int)dr["Sex"];

And I seem to get exactly the same error on the same line.
>In the database table, Sex has a data type=smallint

So the Sex field can have a range of values from -32,768 to 32,767...?
Hey, we like our site to support all types. ;-) Seriously, it's coming from
a RadioButtonList and just seemed to make more sense to use an int. Besides,
I don't see how a database can store a bit field using less than a byte
anyway.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Jan 11 '08 #5
Actually, it looks like dr["Sex"] was NULL. But I thought I was testing for
that.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

"Peter Bromberg [C# MVP]" <pb*******@yaho o.NoSpamMaam.co mwrote in message
news:23******** *************** ***********@mic rosoft.com...
What type is client.Sex? Looks like whatever it is, it cannot accept int
as a
value. Unless the Convert of the (int)dr["Sex"] is failing because it
itself is not an integer.

-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
MetaFinder: http://www.blogmetafinder.com
"Jonathan Wood" wrote:
>The following code raises the error "Specified cast is not valid."

MembershipUser user = Membership.GetU ser(userId);
DataSet ds = DataLayer.ExecQ ueryData("SELEC T * FROM mc_Clients WHERE
UserId='" + userId.ToString () + "'");
if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count ==
0)
return null;
ClientEx client = new ClientEx();
client.ClientDa ta = new Client();
client.ClientDa ta.Email = user.UserName;
client.ClientDa ta.UserID = user.ProviderUs erKey;
client.ClientDa ta.LastLogin = user.LastLoginD ate;
DataRow dr = ds.Tables[0].Rows[0];

// ...

if (!Convert.IsDBN ull(dr["Sex"]))
client.Sex = (int)dr["Sex"]; <<== ERROR HERE!

// ...

In the database table, Sex has a data type=smallint and nullable=True,
and
client.Sex has a data type of int.

If I attempt to examine the contents of dr["Sex"] in the debugger, it
shows
a value of 0x0000. If I attempt to examine the contents of (int)dr["Sex"]
in
the debugger, it shows an error about not being able to unbox (sorry I no
longer have the exact text).

Any suggestions?

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Jan 11 '08 #6
"Jonathan Wood" <jw***@softcirc uits.comwrote in message
news:u4******** **********@TK2M SFTNGP03.phx.gb l...
>>The following code raises the error "Specified cast is not valid."

Yes, it would do...
>> if (!Convert.IsDBN ull(dr["Sex"]))

if (dr["Sex"] != DBNull.Value)

So what does that mean? Does that mean dr["Sex"] was, in fact, null but my
check was wrong?
I believe so...
And what the heck does Convert.IsDBNul l() do? This seemed to work on some
other fields.
It (supposedly) does exactly the same thing:
http://msdn2.microsoft.com/en-us/lib....isdbnull.aspx

but I've found it to be an extremely unreliable way of checking for a null
value in a database field...
Actually, I just tried this:

if (dr["Sex"] != DBNull.Value)
client.Sex = (int)dr["Sex"];

And I seem to get exactly the same error on the same line.
Hmm - OK... Set a breakpoint on the first line above and, in the Immediate
window, inspect dr["Sex"]
>>In the database table, Sex has a data type=smallint

So the Sex field can have a range of values from -32,768 to 32,767...?

Hey, we like our site to support all types. ;-) Seriously, it's coming
from a RadioButtonList and just seemed to make more sense to use an int.
I don't understand the thinking behind that at all...
Besides, I don't see how a database can store a bit field using less than
a byte anyway.
SQL Server (and several other RDBMS) can:

http://msdn2.microsoft.com/en-us/lib...atype.bit.aspx

My slightly tongue-in-cheek point was that you're using a larger datatype
than is necessary... For gender, I tend to use char(1)...
--
Mark Rae
ASP.NET MVP
http://www.markrae.net

Jan 11 '08 #7
I figured this out. It only works if I cast using (short) insteat of (int).
I have no idea why that is--converting from a 16-bit integer to a 32-bit
integer is a trivial task, in fact one that the compiler still does after my
change.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

"Jonathan Wood" <jw***@softcirc uits.comwrote in message
news:%2******** **********@TK2M SFTNGP04.phx.gb l...
The following code raises the error "Specified cast is not valid."

MembershipUser user = Membership.GetU ser(userId);
DataSet ds = DataLayer.ExecQ ueryData("SELEC T * FROM mc_Clients WHERE
UserId='" + userId.ToString () + "'");
if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
return null;
ClientEx client = new ClientEx();
client.ClientDa ta = new Client();
client.ClientDa ta.Email = user.UserName;
client.ClientDa ta.UserID = user.ProviderUs erKey;
client.ClientDa ta.LastLogin = user.LastLoginD ate;
DataRow dr = ds.Tables[0].Rows[0];

// ...

if (!Convert.IsDBN ull(dr["Sex"]))
client.Sex = (int)dr["Sex"]; <<== ERROR HERE!

// ...

In the database table, Sex has a data type=smallint and nullable=True, and
client.Sex has a data type of int.

If I attempt to examine the contents of dr["Sex"] in the debugger, it
shows a value of 0x0000. If I attempt to examine the contents of
(int)dr["Sex"] in the debugger, it shows an error about not being able to
unbox (sorry I no longer have the exact text).

Any suggestions?

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com
Jan 11 '08 #8
Mark,
>And I seem to get exactly the same error on the same line.

Hmm - OK... Set a breakpoint on the first line above and, in the Immediate
window, inspect dr["Sex"]
I described that in my original post. At any rate, the fix was to type cast
to a short instead of an int, which doesn't seem like it should be the case.
>Besides, I don't see how a database can store a bit field using less than
a byte anyway.

SQL Server (and several other RDBMS) can:

http://msdn2.microsoft.com/en-us/lib...atype.bit.aspx
My slightly tongue-in-cheek point was that you're using a larger datatype
than is necessary... For gender, I tend to use char(1)...
I didn't see where that link talked about the actual amount of storage used
to store bits in the database, I suppose it's possible to optimize bit
fields if they are stored contiguously, rather than with the other fields in
the same row, but I wouldn't have thought that's how it's done. At any rate,
I've used both char(1) and bit but I'm more comfortable using smallint in
this particular case.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Jan 11 '08 #9
"Jonathan Wood" <jw***@softcirc uits.comwrote in message
news:uZ******** ******@TK2MSFTN GP05.phx.gbl...
Perhaps a byte would be better
Yes it would - or a char(1)...
isn't that a tinyint?
Yes - a tinyint and a char(1) both occupy one byte...
a single byte is the least amount of storage space that most fields could
occupy.
Correct, apart from bit fields for boolean values, but that doesn't apply
here...
--
Mark Rae
ASP.NET MVP
http://www.markrae.net

Jan 12 '08 #10

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

Similar topics

16
2184
by: Jace Benson | last post by:
Ok I have read alot of things on zend.com, php.net and other sites went to the wikibooks to try to understand how to use a class. I have this project I want to do that I am sure would work great with a class. I just don't grasp the whole concept, and how to do it. I want to make a Collectable Card Game Draft Engine...(if any of you play VS System, LOTR, Magic: The Gathering, you know what I am talking about.) It would be way to...
12
4043
by: AFN | last post by:
I am running the code below to generate XML from a data table. But some fields in the data table are Null for every record. Suppose field5 has a null database value. I would expect to see: <field5></field5> or <field5 /> but instead it doesn't even show the field at all for those records where field5 is Null! Instead it just shows: <field4>Whatever</field4>
10
1306
by: Wayne Wengert | last post by:
I am using a datareader (dr1) to read through rows returned from a query. I am getting the error: "No data exists for the row/column." at the "If IsDbNull..." in the code below. The field "Photo1" does exist and in some rows it is null, in others it may be an empty string and in others it may have a file name. I don't understand exactly what the system is complaining about here? Wayne
13
4906
by: rdemyan via AccessMonster.com | last post by:
My front-end code manually links to the backend file. I was wondering what stops Access from linking to the system tables in the backend file. Is it just by virtue that they are hidden? This has recently come up because I've been playing around with converting my front end to A2003 format. At some point, I had a corruption issue with a system file MSStorage something. Access kept saying it couldn't find it. When I looked in the db...
19
2243
by: so many sites so little time | last post by:
the table is head the colunm is called body <?php //show_site.php // This script retrieves blog entries from the database. // Address error handing. ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); // Connect and select.
20
3466
by: Wes Groleau | last post by:
I was doing update statements in SQL Server 2000. I have a table with over 16 million rows. It came from several hundred delimited text files, and two of the columns are file ID (int) and Line # (int) Structure is X12 (835). For those unfamiliar with that, each file has one to many BPR lines; each BPR line has zero to many CLP lines, each of those has zero to many
21
2047
by: jehugaleahsa | last post by:
Hello: I had an hour-long discussion with my boss today. Last night, right before I dozed off, I realized some of his code resulted in duplicate processing. I tried to explain it to him and he kept saying, "I'm afraid to say it's 'OK' to change it because everything I did was for a reason." Well, I know better. My boss' old code is written in some cryptic C file with Oracle precompiler macros barfed all over it. Once I figured out how...
3
1943
by: Hazza | last post by:
Hi, I am using PHP and mysql to create a website. I am fairly new to PHP, and thus am grateful to anyone who helps! Firstly I am running a homepage, that displays additional content if a user has logged in. I set a loggedin session in the log in page, which I have tested and works fine in other scripts. I am displaying news on the homepage (which is stored in a mysql database), and this works fine when the user accesses the homepage...
3
1547
by: Ben Thomas | last post by:
Hello, I have the following code which I don't understand why it works : #include <iostream> using namespace std; void DontWork (unsigned int& i) { cout << i << endl; }
0
8203
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
8642
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...
0
7203
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
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
5576
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
4094
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4206
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2630
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
1
1815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.