c# - SQLDataReader Cast Issues

Posted on 2011-10-24
Last Modified: 2012-05-12
Not a c# guru.  Just writing a quick script but getting issues.  See code box.

The code is part of a script that pulls SQL Server data and puts to Excel.

Keep getting cast errors.  Trying to account for that by checking the column type.

I need the code to be as dynamic as possible, so that it spits out any type of data, regardless if it's a date, integer, or string.

Here's my last error:

Unable to cast object of type 'System.Decimal' to type 'System.String'

Looking for a better what of doing???

for (int i = 0; i < dr2.FieldCount; i++)

	if (dr2.GetDataTypeName(i).ToString() == "datetime")
	    ws.Cells[row, col] = (dr2.GetDateTime(i).ToString("MM/dd/yyyy"));
	else if (dr2.GetDataTypeName(i).ToString() == "int")
	    ws.Cells[row, col] =dr2.GetInt32(i).ToString();
	    ws.Cells[row, col] = dr2.GetString(i); ;


Open in new window

Question by:carsRST
    LVL 74

    Accepted Solution

    Try changing line 14 from

    ws.Cells[row, col] = dr2.GetString(i); ;

    Open in new window


    ws.Cells[row, col] = dr2[i].ToString();

    Open in new window

    LVL 16

    Author Closing Comment

    Thanks, man!

    I greatly appreciate your help and time.
    LVL 74

    Expert Comment

    by:käµfm³d 👽
    NP, glad to help. Just be aware that that particular change will cause whatever type of object is housed in that column to have its default ToString method called. It may be of no consequence for the data you are working with, but it could come into play if one of the columns you were returning were of type xml on the database, for example.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Live - One-on-One C# Help from Top Experts

    Solve your toughest problems, fast.
    C# experts are online now and ready to help you.

    Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
    Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    This video discusses moving either the default database or any database to a new volume.

    779 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

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now