473,506 Members | 16,994 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why "Specified cast is not valid" error?

Hello,

I'm coding a webform application in C# (ASP.NET 1.1 SP1 with VS.NET 2003 Pro
on WinXP SP2 using IIS 5.1).

I created a seperate "data" class to house all the MySQL connection and sql
command methods. This is exactly what the Microsoft Data Access Application
Block assembly does but I coded my own simple, custom class.

I have a method named "ExecuteAggregate" that takes in a sql string like
"SELECT COUNT(*) FROM users", executes it like ExecuteScalar() does and
returns an object typed value. Here is the code below:

***CODE BLOCK***

public static object ExecuteAggregate(string SQL)
{

MySqlCommand myCmd = new MySqlCommand(SQL, myConn);

object retval = myCmd.ExecuteScalar();

return retval;

}

***CODE BLOCK***

I use the above method in the page_load event as shown below. The project
builds without error or warning but the page errors out when it executes.

***CODE BLOCK***

private void Page_Load(object sender, System.EventArgs e)
{

string userCount;

Data.Connect();

//>>>>>"Specified cast is not valid." exception occurs on next line!

userCount = (string)Data.ExecuteAggregate("SELECT COUNT(*) FROM users");

lblBalance.Text = userCount;

Data.Disconnect();

}

***CODE BLOCK***

I have no idea why this is erroring out when executing and not during
building. Convert.ToInt32() fixes this but I would like to know why a C#
cast will not.

Thanks for your help in advance!
Nov 16 '05 #1
13 28231
Try
convert.toString(Data.ExecuteAggregate("SELECT COUNT(*) FROM users"));

"Jack MacRank" wrote:
Hello,

I'm coding a webform application in C# (ASP.NET 1.1 SP1 with VS.NET 2003 Pro
on WinXP SP2 using IIS 5.1).

I created a seperate "data" class to house all the MySQL connection and sql
command methods. This is exactly what the Microsoft Data Access Application
Block assembly does but I coded my own simple, custom class.

I have a method named "ExecuteAggregate" that takes in a sql string like
"SELECT COUNT(*) FROM users", executes it like ExecuteScalar() does and
returns an object typed value. Here is the code below:

***CODE BLOCK***

public static object ExecuteAggregate(string SQL)
{

MySqlCommand myCmd = new MySqlCommand(SQL, myConn);

object retval = myCmd.ExecuteScalar();

return retval;

}

***CODE BLOCK***

I use the above method in the page_load event as shown below. The project
builds without error or warning but the page errors out when it executes.

***CODE BLOCK***

private void Page_Load(object sender, System.EventArgs e)
{

string userCount;

Data.Connect();

//>>>>>"Specified cast is not valid." exception occurs on next line!

userCount = (string)Data.ExecuteAggregate("SELECT COUNT(*) FROM users");

lblBalance.Text = userCount;

Data.Disconnect();

}

***CODE BLOCK***

I have no idea why this is erroring out when executing and not during
building. Convert.ToInt32() fixes this but I would like to know why a C#
cast will not.

Thanks for your help in advance!

Nov 16 '05 #2
Hi,

Have you tried:

userCount = Data.ExecuteAggregate("SELECT COUNT(*) FROM users").ToString();

instead of using a casting ?
if still getting error, assig the return value to an object instance and put
a break point in the next line to see what you are getting as response.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Jack MacRank" <ja**@macrank.com> wrote in message
news:aP*****************@fe1.columbus.rr.com...
Hello,

I'm coding a webform application in C# (ASP.NET 1.1 SP1 with VS.NET 2003
Pro on WinXP SP2 using IIS 5.1).

I created a seperate "data" class to house all the MySQL connection and
sql command methods. This is exactly what the Microsoft Data Access
Application Block assembly does but I coded my own simple, custom class.

I have a method named "ExecuteAggregate" that takes in a sql string like
"SELECT COUNT(*) FROM users", executes it like ExecuteScalar() does and
returns an object typed value. Here is the code below:

***CODE BLOCK***

public static object ExecuteAggregate(string SQL)
{

MySqlCommand myCmd = new MySqlCommand(SQL, myConn);

object retval = myCmd.ExecuteScalar();

return retval;

}

***CODE BLOCK***

I use the above method in the page_load event as shown below. The project
builds without error or warning but the page errors out when it executes.

***CODE BLOCK***

private void Page_Load(object sender, System.EventArgs e)
{

string userCount;

Data.Connect();

//>>>>>"Specified cast is not valid." exception occurs on next line!

userCount = (string)Data.ExecuteAggregate("SELECT COUNT(*) FROM users");

lblBalance.Text = userCount;

Data.Disconnect();

}

***CODE BLOCK***

I have no idea why this is erroring out when executing and not during
building. Convert.ToInt32() fixes this but I would like to know why a C#
cast will not.

Thanks for your help in advance!

Nov 16 '05 #3
Jack MacRank <ja**@macrank.com> wrote:

<snip>
***CODE BLOCK***

private void Page_Load(object sender, System.EventArgs e)
{

string userCount;

Data.Connect();

//>>>>>"Specified cast is not valid." exception occurs on next line!

userCount = (string)Data.ExecuteAggregate("SELECT COUNT(*) FROM users");

lblBalance.Text = userCount;

Data.Disconnect();

}

***CODE BLOCK***

I have no idea why this is erroring out when executing and not during
building. Convert.ToInt32() fixes this but I would like to know why a C#
cast will not.


Your C# is expecting the reference returned by Data.ExecuteAggregate to
*be* a string. It's not. Try casting to int instead - or print out
Data.ExecuteAggregate(...).GetType() to find out what type is actually
returned.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
"Rob Lykens" wrote
Try
convert.toString(Data.ExecuteAggregate("SELECT COUNT(*) FROM users"));


Yes Rob, that does work and that's what I meant to write at the bottom of my
original message, not Int32(). But why doesn't cast work in this situation?
Microsoft's Data Access Application Block examples have the exact structure
of my code but it errors out when executed.

Thanks
Nov 16 '05 #5
hi
i guess it is not working becasue that you are custing it as String , while
the returned value is int . ( and this is what is done by the
convertToInt())
try
userCount =(int) Data.EcexuteAggregate("your query");
hope this is it
Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSCr

Nov 16 '05 #6
Ignacio Machin ( .NET/ C# MVP ) wrote
Hi,

Have you tried:

userCount = Data.ExecuteAggregate("SELECT COUNT(*) FROM
users").ToString();


Ignacio, this works perfect but in other places I will need to cast/convert
it as an int type. I will play around with breakpoints before the object is
returned to see if anything funny is going on but I'm still wondering why a
simple cast won't work.

Thanks!
Nov 16 '05 #7

"Jack MacRank" <ja**@macrank.com> wrote in message
news:aP*****************@fe1.columbus.rr.com...
Hello,

I'm coding a webform application in C# (ASP.NET 1.1 SP1 with VS.NET 2003
Pro on WinXP SP2 using IIS 5.1).

I created a seperate "data" class to house all the MySQL connection and
sql command methods. This is exactly what the Microsoft Data Access
Application Block assembly does but I coded my own simple, custom class.

I have a method named "ExecuteAggregate" that takes in a sql string like
"SELECT COUNT(*) FROM users", executes it like ExecuteScalar() does and
returns an object typed value. Here is the code below:

***CODE BLOCK***

public static object ExecuteAggregate(string SQL)
{

MySqlCommand myCmd = new MySqlCommand(SQL, myConn);

object retval = myCmd.ExecuteScalar();

return retval;

}

***CODE BLOCK***

I use the above method in the page_load event as shown below. The project
builds without error or warning but the page errors out when it executes.

***CODE BLOCK***

private void Page_Load(object sender, System.EventArgs e)
{

string userCount;

Data.Connect();

//>>>>>"Specified cast is not valid." exception occurs on next line!

userCount = (string)Data.ExecuteAggregate("SELECT COUNT(*) FROM users");

lblBalance.Text = userCount;

Data.Disconnect();

}

***CODE BLOCK***

I have no idea why this is erroring out when executing and not during
building. Convert.ToInt32() fixes this but I would like to know why a C#
cast will not.

Thanks for your help in advance!


I'd advise strongly for the Convert.ToXXX() approach, as it won't break your
code if a future version of MySQL (or the provider) decides to return the
COUNT(*) as long instead of int.
The C# cast works as follows:

- Check if the object is exactly of the requested type / implements the
requested interface (null is allowed for reference types)
- Throw an exception if it isn't
- Assign the reference / unbox for value types

On the other hand, the Convert.ToXXX(object) function makes it's best effort
to convert the value, if it's possible. So it can convert byte, sbyte,
short, etc... to int. And the overhead of calling the conversion function is
absolutely insignificant, as the time spent in the ExecuteScalar() method is
thousands of times longer.

HTH,
Stefan
Nov 16 '05 #8
Stefan,

I set a breakpoint and looked at the GetType() of "retval" after the query
executed. I was surprised to see it was of Int64 type. I didn't know
C#/.NET automatically converted an object variable to another type...I
thought it would just be a generic object type and then I could cast it to
whatever I wanted it to.

I'm still a little confused why I can't cast an Int64 to String but I will
take your advice and use .ToString() and Convert.ToInt32() when I want a
string or integer.

Thanks to everyone who responded to my question!
Nov 16 '05 #9
Hi,

the query you have should not return a string, hence you need to convert
that value.
You may cast it to a numeric value ( maybe excepting byte ) without much
problem

Now, my advice in this cases is play safe and use Convert.XXX a casting
may be problematic, even for numeric values. it depends of the DB engine
internal types.
It should not intruduce much overhead calling Convert.ToString( string )
or Convert.ToInt32( int ) so the performance should not be affected

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Jack MacRank" <ja**@macrank.com> wrote in message
news:K9*****************@fe1.columbus.rr.com...
Ignacio Machin ( .NET/ C# MVP ) wrote
Hi,

Have you tried:

userCount = Data.ExecuteAggregate("SELECT COUNT(*) FROM
users").ToString();


Ignacio, this works perfect but in other places I will need to
cast/convert it as an int type. I will play around with breakpoints
before the object is returned to see if anything funny is going on but I'm
still wondering why a simple cast won't work.

Thanks!

Nov 16 '05 #10
The result is an int and can't be cast to type string. Call the
ToString() method rather then typecast.
"Jack MacRank" <ja**@macrank.com> wrote in message news:<aP*****************@fe1.columbus.rr.com>...
Hello,

I'm coding a webform application in C# (ASP.NET 1.1 SP1 with VS.NET 2003 Pro
on WinXP SP2 using IIS 5.1).

I created a seperate "data" class to house all the MySQL connection and sql
command methods. This is exactly what the Microsoft Data Access Application
Block assembly does but I coded my own simple, custom class.

I have a method named "ExecuteAggregate" that takes in a sql string like
"SELECT COUNT(*) FROM users", executes it like ExecuteScalar() does and
returns an object typed value. Here is the code below:

***CODE BLOCK***

public static object ExecuteAggregate(string SQL)
{

MySqlCommand myCmd = new MySqlCommand(SQL, myConn);

object retval = myCmd.ExecuteScalar();

return retval;

}

***CODE BLOCK***

I use the above method in the page_load event as shown below. The project
builds without error or warning but the page errors out when it executes.

***CODE BLOCK***

private void Page_Load(object sender, System.EventArgs e)
{

string userCount;

Data.Connect();

//>>>>>"Specified cast is not valid." exception occurs on next line!

userCount = (string)Data.ExecuteAggregate("SELECT COUNT(*) FROM users");
userCount = Data.ExecuteAggregate("SELECT COUNT(*) FROM
users").ToString()

lblBalance.Text = userCount;

Data.Disconnect();

}

***CODE BLOCK***

I have no idea why this is erroring out when executing and not during
building. Convert.ToInt32() fixes this but I would like to know why a C#
cast will not.

Thanks for your help in advance!

Nov 16 '05 #11
Jack MacRank <ja**@macrank.com> wrote:
I set a breakpoint and looked at the GetType() of "retval" after the query
executed. I was surprised to see it was of Int64 type. I didn't know
C#/.NET automatically converted an object variable to another type...I
thought it would just be a generic object type and then I could cast it to
whatever I wanted it to.

I'm still a little confused why I can't cast an Int64 to String but I will
take your advice and use .ToString() and Convert.ToInt32() when I want a
string or integer.

Thanks to everyone who responded to my question!


I *strongly* suggest you abandon database access for the moment and
read a good book on the basics of .NET, in particular the type system.
Then read up on what casts do in C#.

I know it may sound like a backward step, but getting a good handle on
the basics is vital for writing decent code. For instance, you don't
always want to call .ToString or Convert.ToInt32() - it depends
entirely on the circumstances.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #12
"Jack MacRank" <ja**@macrank.com> wrote:
Convert.ToInt32() fixes this but I would like to know why a C# cast will
not.

The 'cast' operator in C# can actually mean all sorts of different things in
different contexts. This can be somewhat confusing, as you've found. I
wrote this a while ago, as it's a common source of confusion:

http://www.interact-sw.co.uk/iangblo.../01/20/casting

Hope that helps.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/
Nov 16 '05 #13


Thanks, I was having the same casting problem and solved it following
your instructions of using the ToString method. I do not understand why
a simple cast will not work on this situation... but is working now.
N.R.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #14

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

Similar topics

0
3610
by: Tao | last post by:
I just upgraded .NET framework to 1.1 and VS.Net to 2003 version and tried to test it out. I created an ASP.NET project using the wizard and tried to run it by hitting "F5". I got an exception:...
1
5808
by: Ron Holmes | last post by:
I posted this question on the Crystal Reports Support site and I am still waiting for an answer. Using Crystal Reports 9.0 Developer Full edition: My Crystal report .RPT file has a Picture box...
0
1499
by: Özden Irmak | last post by:
Hello, In my application, I've to cast DocumentDesigner class to my own derived class,MyDocumentDesigner, in order to reach the protected properties in DocumentDesigner class. But everytime I...
8
1785
by: Charles | last post by:
I do not understand why I am getting a "Specified cast is not valid" error, since it has worked before. Something has changed and I am not really sure what it could be. I am looking for something...
2
3082
by: Fabian | last post by:
Hi, I work with asp.net 2.0 and I have a intermittent error, only happens a few times a day. In the page I evaluate a Query String and then I get data form a database. The code snipped: ...
1
1422
by: Kevin O`Brien | last post by:
I was reading my new asp.net book last night and thought I'd give mobile devices a go. I use Web Matrix, however when I went to create a new mobile page this morning, it displayed a dialog box...
3
3190
by: Jayyde | last post by:
Not sure why all of a sudden this line of code: cmbProductCategoryTreeDisplayName.SelectedIndex = 0; is producing a "Specified cast is not valid error". In the watch it has 1 item in it at...
3
3680
by: keithb | last post by:
Using a GridView, I get a "Specified cast is not valid" error when binding the Visible propery of a hyperlink control to a DataTable text field. The error goes away if I replace the data binding...
3
12415
by: =?Utf-8?B?UGF1bCBQcmV3ZXR0?= | last post by:
I'm attempting to use LINQ to insert a record into a child table and I'm receiving a "Specified cast is not valid" error that has something to do w/ the keys involved. The stack trace is: ...
0
7307
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,...
0
7370
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...
0
5614
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,...
0
4701
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...
0
3188
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...
0
3177
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1532
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 ...
1
755
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
409
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.