?
Solved

System.InvalidCastException: Specified cast is not valid, Microsoft Visual Studio, C#

Posted on 2008-10-14
7
Medium Priority
?
945 Views
Last Modified: 2013-11-26
I am writing a program which runs a stored procedure to return the data, then output the content to a CSV file.   When running my stored procedure, I get all the values back.  However, when I run the program, it stops what iit's doing and gives me the following error:

************** Exception Text **************
System.InvalidCastException: Specified cast is not valid.


I took a look at the CSV file and it populated 23 out of the 57 lines before it gives me this error message.  After doing some testing, I took out the following line and it worked successfully:

Decimal decDiscount = (Decimal)rowA["Discount"];

Can someone please help me solve this issue? I'm not sure what i'm doing wrong with the "Discount" column of the Stored Procedure.  The "Total" column has no problems, but its only the "Discount" column.  Both columns are the same data type of "money".
this.spTableAdapter.Fill(this.twOLTPDDataSet.spSproc);
DataView data = new DataView(twOLTPDDataSet.spSproc);
 
//Begin each row cycle
foreach (DataRowView rowA in currMinorData)
{
    string strCustomer = (string)rowA["Customer"];
    string strName = (string)rowA["Name"];
 
    Decimal decTotal = (Decimal)rowA["Total"];
    string strTotal = decTotal.ToString();
 
    Decimal decDiscount = (Decimal)rowA["Discount"];
    string strDiscount = decDiscount.ToString();
 
    Write Comma Delimiter to the file
    CorporateSpending.WriteLine(strCustomer + "," + strName + "," + strTotal + "," + strDiscount);
 
}

Open in new window

0
Comment
Question by:IndianaTech
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 22

Accepted Solution

by:
p_davis earned 1800 total points
ID: 22714641
try the conversion
Convert.ToDecimal(rowA["Discount"]);
instead of the cast
0
 
LVL 13

Assisted Solution

by:TechTiger007
TechTiger007 earned 200 total points
ID: 22714705
If you have null values for Discount then the type casting will fail.
Check if the value is DBNull.value or null and then type cast it to Decimal using Convert.ToDecimal only if it is valid.
0
 

Author Comment

by:IndianaTech
ID: 22714777
@p_davis: I updated my code to reflect your change.
and I am getting a different error back this time:

************** Exception Text **************
System.InvalidCastException: Object cannot be cast from DBNull to other types.
   at System.DBNull.System.IConvertible.ToDecimal(IFormatProvider provider)
   at System.Convert.ToDecimal(Object value)
************** Exception Text **************

I looked at the results of the CSV file and it has 22 lines in the file.  I looked at Query Analyzer and the 23rd row doesn't have any Null values in it.  I'm not too sure why it would be telling me it cannot cast from DBNull to other types.
string strDiscount = Convert.ToDecimal(rowA["Discount"]).ToString();

Open in new window

0
Interactive Way of Training for the AWS CSA Exam

An interactive way of learning that will help you visualize core concepts so that you can be more effective when taking your AWS certification exam.  Built for students by a student to help them understand the concepts that they are being taught.

 
LVL 22

Expert Comment

by:p_davis
ID: 22714823
add what Tech Suggested with the

if(rowA["Discount"] != DbNull.Value)
   strDiscount = Convert.ToDecimal(rowA["Discount"]).ToString();

wait why are you converting to decimal and then to string?

what about

String strDiscount = String.Format("{0}:c", rowA["Discount"]);
0
 
LVL 22

Expert Comment

by:p_davis
ID: 22714850
sorry that would be...

String strDiscount = String.Format("{1:c}", rowA["Discount"]);
0
 

Author Comment

by:IndianaTech
ID: 22714950
@p_davis: Have a problem with the DbNull.Value.

When building it, i got an error that says:
"The name 'DbNull' doe snot exist in the current context."
0
 
LVL 22

Expert Comment

by:p_davis
ID: 22714977
sorry

DBNull
0

Featured Post

How to Create Failover DNS Record Sets in Route 53

Route 53 has the ability to easily configure DNS record sets specifically for failover scenarios. These failover record sets can be configured to failover to full-blown deployments in other regions or to a static HTML page that informs your customers of the issue.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

718 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question