473,320 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Can't get past Specified cast is not valid error

I have a datagrid codebehind script that takes data from sql dbase and
displays it in a footer row as a total. One column has amount_dollars
(which works fine), while another has new sales (which is "newstotal"),
but I'm getting an error (System.InvalidCastException: Specified cast
is not valid) from the newstotal line:

price = (Decimal)(rowData["Amount_Dollars"]);
newstotal = (rowData["News"]);

newstotal is an integer, just wondering what datatype i should use
(whereas 'price' is a money datatype, and I can format it as Decimal,
but I just want the newstotal to be a simple integer. )Using (Integer)
or (short) in front of (rowData["News"]); give me the Specified cast
not valid error.

????
..netsports

Nov 17 '05 #1
5 3930
I'm no expert, but have you tried:
newstotal = Convert.ToInt32(rowData["News"]);

Bob Graham

..Net Sports wrote:
I have a datagrid codebehind script that takes data from sql dbase and
displays it in a footer row as a total. One column has amount_dollars
(which works fine), while another has new sales (which is "newstotal"),
but I'm getting an error (System.InvalidCastException: Specified cast
is not valid) from the newstotal line:

price = (Decimal)(rowData["Amount_Dollars"]);
newstotal = (rowData["News"]);

newstotal is an integer, just wondering what datatype i should use
(whereas 'price' is a money datatype, and I can format it as Decimal,
but I just want the newstotal to be a simple integer. )Using (Integer)
or (short) in front of (rowData["News"]); give me the Specified cast
not valid error.

????
.netsports


Nov 17 '05 #2
".Net Sports" <ba********@cox.net> wrote in message news:11**********************@o13g2000cwo.googlegr oups.com...
newstotal = (rowData["News"]);
newstotal is an integer, just wondering what datatype i should use


Try asking it and/or printing a message in a debug window,

System.Diagnostics.Debug.WriteLineIf( ( rowData["News"] != null ), rowData["News"].GetType( ).FullName );

If its a string (even if it's a string containing a number, C# is still
strict about these things), then Parse( ) it,

newstotal = int.Parse( rowData[ "News"]);

Note that this'll throw a FormatException if the contents of the
string aren't really a number. If that can happen you could use
Double.TryParse( ) with some flags to be a little more accom-
modating of currency signs or thousands separators appearing
in the string and then cast the double result to an integer.
Derek Harmon
Nov 17 '05 #3
Don't forget that rowData["News"] could be DBNull.Value, if the value
in the database is null, in which none of the solutions here will work.
You should always test for that, first.

After that, I would try Derek's suggestion to display the data type.
That will tell you the best type to which to cast. (Have you tried
long?)

Nov 17 '05 #4
As a further idea, I wrote a method for each data type:

public int DBValueToInt(object rowValue, int defaultValue)
{
if (rowValue.Equals(DBNull.Value))
{
return defaultValue;
}
else
{
return (int)rowValue;
}
}

then I always say:

int newstotal = DataHandler.DBValueToInt(rowData["News"], 0);

which takes care of the DBNull case without writing tons of code. I
have similar methods for decimal, string, boolean, etc.

Nov 17 '05 #5
In message <11*********************@f14g2000cwb.googlegroups. com>, Bruce
Wood <br*******@canada.com> writes
As a further idea, I wrote a method for each data type:

public int DBValueToInt(object rowValue, int defaultValue)
{
if (rowValue.Equals(DBNull.Value))
{
return defaultValue;
}
else
{
return (int)rowValue;
}
}

then I always say:

int newstotal = DataHandler.DBValueToInt(rowData["News"], 0);

which takes care of the DBNull case without writing tons of code. I
have similar methods for decimal, string, boolean, etc.


Similarly, I have a SafeRowWrapper class.

public Foo(DataRow dr)
{
SafeRowWrapper sr = new SafeRowWrapper(dr);
this.id=sr.GetIntID("ID");
this.title=sr.GetString("Title");
this.description=sr.GetString("Description");
}

It handles DBNulls and also manages certain conventions I use (i.e.
GetInt("Total") will return 0 if total == DBNull, GetIntID("CurrencyID")
will return -1 for CurrencyID == DBNull. The point of this convention is
this:

class Currency
{
......
public static Currency GetInstanceByID(int id)
{
if(id == -1)
{
return Currency.Empty;
}
.....
}
}

--
Steve Walker
Nov 17 '05 #6

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

Similar topics

4
by: SRLoka | last post by:
I have an application that has five threads. All five threads write to the same MSMQ. All five threads are using the same global instance to send data to the MSMQ server(on same machine)....
3
by: PK9 | last post by:
I am looking for assistance in pinpointing the cause of the following exception. I am getting a "Specified Cast is not valid" exception on my page. I am trying to populate a datagrid. One of my...
3
by: VB Programmer | last post by:
I am setting up forms authentication. In my code I keep getting this error. Any ideas? Error.... Server Error in '/LandOLots' Application....
0
by: QA | last post by:
I am using a Business Scorecard Accelarator in a Sharepoint Portal 2003 using SQL Server 2005 I am getting the following error: Error,5/7/2005 10:50:14 AM,580,AUE1\Administrator,"Specified cast is...
3
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...
8
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is...
2
by: Kashiefah | last post by:
Hi, I keep on receiving this error when I click on the edit email link from the datagrid:Specified cast is not valid. Description: An unhandled exception occurred during the execution of the...
4
by: John Rogers | last post by:
Can someone help me out if possible with this error when running a program. I have this code in the program //------------------------------------------- System.Data.OleDb.OleDbCommand vCommand...
2
by: vinrin | last post by:
Thank for your answer. :-) call CheckEmptyNode (treeview) public void CheckEmptyNode( Object N ) { Microsoft.Web.UI.WebControls.TreeNode menuNode = null; ...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.