Unable to cast object of type 'System.Int32' to type 'System.String'. c# error

have a c# data reader that is returning data all has been going well and i put in a null check if // '(DbReaderLinkedin.IsDBNull(i)) { }'
without this line the data retunrs and can read the varable  into
//'col = DbReaderLinkedin.GetString(i);'  ok

as soon as i add this line if ///''(DbReaderLinkedin.IsDBNull(i)) { } the system when it gets to
''col = DbReaderLinkedin.GetString(i); throws up a
Unable to cast object of type 'System.Int32' to type 'System.String'.

why does it do this.... any ideas

     if (DbReaderLinkedin.IsDBNull(i)) { }
        else
           {

this throws up the same problem

                               string retrievedValue = "";
                              if (DbReaderLinkedin.IsDBNull(i)) { retrievedValue = ""; }
                            else { retrievedValue = DbReaderLinkedin.GetString(i); }


                               
   

                               
 
 




sydneyguyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bill NolanOwner, Lead Technology ProgrammerCommented:
It is not able to cast int to string, regardless of your conditional check.  You appear to be iterating with 'i', but do not show the code; my guess is you have a simple logic error in your loop.
0
Naman GoelPrinciple Software engineerCommented:
what is i??

is it object??

here the safe way to do this is like

object colobject = DbReaderLinkedin.GetString(i);

if(typeOf(colobject)== String.GetType())
{
    col= object.ToString();
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sydneyguyAuthor Commented:
no logic error, what i am doing is associating the dbreader returned data into an array and that
works fine, what does not work is when the dbreader value is a null, so we then test for a null,
with if (DbReader.IsDBNull(i)) { } now if its not a null and its a value that would pass the check then move into col = DbReader.GetString(i); which would normally work unless you test for null then it falls over with the "Unable to cast object of type 'System.DBNull' to type 'System.String'."
so it falls over if theres a null, but if its not a null and passes to the col=dbreader ect line were it fails with the unable to cast exception, after it has been tested for null, but this woudl work if not tested for null

seems that once you read it changes something

for (int i = 0; i < fCount; i++)
  {

                                col = DbReader.GetString(i);
                                // STORE IN THE ARRAY THE INFO FOR THE FIELDS READY TO PASS
                                recinfo[i] = col;
}

 for (int i = 0; i < fCount; i++)
  {

                 if (DbReader.IsDBNull(i)) { }
                    else
                  {                  
                                col = DbReader.GetString(i);
                                // STORE IN THE ARRAY THE INFO FOR THE FIELDS READY TO PASS
                                recinfo[i] = col
                  }
}

Open in new window

0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Naman GoelPrinciple Software engineerCommented:
so just read the value and store in some temperory object check for DBNULL or anything and the extract that value in string.

datareader will move forward as soon as you will read the value.
0
sydneyguyAuthor Commented:
but i am not reading the data reader as such i am reading the result of the datareader
col = DbReader.GetString(i); i am cycling through the fields of the data reader and can sucessfully do this  for the whle contents of the sql statment 16 times, in this case, trouble begins when the datarader
col = DbReader.GetString(3); in this case is null and you cannot convert null to string via a
 col = DbReader.GetString(3); so i think test for a null using if (DbReader.IsDBNull(i)) { } but if its not a null and  moves to the statement the valid value that woudl normally work no longer works and throws up an exception,
  col = DbReaderLinkedin.GetString(0);
                            col = DbReaderLinkedin.GetString(0);
                            col = DbReaderLinkedin.GetString(0);
if i run this code three times it works 3 times so its not the read that changes any thing




0
sydneyguyAuthor Commented:
 if (DbReaderLinkedin.IsDBNull(0)) { }
                            else
                            {
                                col = DbReaderLinkedin.GetString(0);
                            }

just did a check with the above code now i know that there is a value in the DbReaderLinkedin.GetString(0);
position, do a read wthout the isdbnull line in and it works fine run the same code again but this time placing in the line isdbnull and the else statment falls over with the exception so i know that the value is the same, there is some else happening
0
sydneyguyAuthor Commented:
his something interesting
if you run the code below which fails before..... but once you put a try in front it runs over and does not throw up an exception, does not jump to the catch routine either which is that you would expect it just works
any ideas????

 try
    {
col = DbReaderLinkedin.GetString(2);

now this line would normaly throw up the exception.....col = DbReaderLinkedin.GetString(2);
as i know that it is null
0
veenaravindCommented:
0
Naman GoelPrinciple Software engineerCommented:
The problem seems to be because of wrong way of usage of IsDbNull method

IsDBNull is calling ReadColumnHeader and it's logic is like this:

 
private void ReadColumnHeader(int i)
{
    if (!this._dataReady)
    {
        throw SQL.InvalidRead();
    }
    if (i >= this._nextColumnDataToRead)
    {
        bool flag = this.IsCommandBehavior(CommandBehavior.SequentialAccess);
        RuntimeHelpers.PrepareConstrainedRegions();
        try
        {
            if (flag)
            {
                if (0 < this._nextColumnDataToRead)
                {
                    this._data[this._nextColumnDataToRead - 1].Clear();
                }
            }
            else if (this._nextColumnDataToRead < this._nextColumnHeaderToRead)
            {
                this.ReadColumnData();
            }
            while (this._nextColumnHeaderToRead <= i)
            {
                this.ResetBlobState();
                if (flag)
                {
                    flag = this._nextColumnHeaderToRead < i;
                }
                _SqlMetaData col = this._metaData[this._nextColumnHeaderToRead];
                if (flag && col.metaType.IsPlp)
                {
                    this._parser.SkipPlpValue(ulong.MaxValue, this._stateObj);
                    this._nextColumnDataToRead = this._nextColumnHeaderToRead;
                    this._nextColumnHeaderToRead++;
                    this._columnDataBytesRemaining = 0L;
                }
                else
                {
                    bool isNull = false;
                    ulong num = this._parser.ProcessColumnHeader(col, this._stateObj, out isNull);
                    this._nextColumnDataToRead = this._nextColumnHeaderToRead;
                    this._nextColumnHeaderToRead++;
                    if (flag)
                    {
                        this._parser.SkipLongBytes(num, this._stateObj);
                        this._columnDataBytesRemaining = 0L;
                        continue;
                    }
                    if (isNull)
                    {
                        this._parser.GetNullSqlValue(this._data[this._nextColumnDataToRead], col);
                        this._columnDataBytesRemaining = 0L;
                        continue;
                    }
                    this._columnDataBytesRemaining = (long) num;
                    if (i > this._nextColumnDataToRead)
                    {
                        this.ReadColumnData();
                    }
                }
            }
        }
        catch (OutOfMemoryException exception3)
        {
            this._isClosed = true;
            if (this._connection != null)
            {
                this._connection.Abort(exception3);
            }
            throw;
        }
        catch (StackOverflowException exception2)
        {
            this._isClosed = true;
            if (this._connection != null)
            {
                this._connection.Abort(exception2);
            }
            throw;
        }
        catch (ThreadAbortException exception)
        {
            this._isClosed = true;
            if (this._connection != null)
            {
                this._connection.Abort(exception);
            }
            throw;
        }
    }
}

Open in new window

private void ReadColumnHeader(int i)
{
    if (!this._dataReady)
    {
        throw SQL.InvalidRead();
    }
    if (i >= this._nextColumnDataToRead)
    {
        bool flag = this.IsCommandBehavior(CommandBehavior.SequentialAccess);
        RuntimeHelpers.PrepareConstrainedRegions();
        try
        {
            if (flag)
            {
                if (0 < this._nextColumnDataToRead)
                {
                    this._data[this._nextColumnDataToRead - 1].Clear();
                }
            }
            else if (this._nextColumnDataToRead < this._nextColumnHeaderToRead)
            {
                this.ReadColumnData();
            }
            while (this._nextColumnHeaderToRead <= i)
            {
                this.ResetBlobState();
                if (flag)
                {
                    flag = this._nextColumnHeaderToRead < i;
                }
                _SqlMetaData col = this._metaData[this._nextColumnHeaderToRead];
                if (flag && col.metaType.IsPlp)
                {
                    this._parser.SkipPlpValue(ulong.MaxValue, this._stateObj);
                    this._nextColumnDataToRead = this._nextColumnHeaderToRead;
                    this._nextColumnHeaderToRead++;
                    this._columnDataBytesRemaining = 0L;
                }
                else
                {
                    bool isNull = false;
                    ulong num = this._parser.ProcessColumnHeader(col, this._stateObj, out isNull);
                    this._nextColumnDataToRead = this._nextColumnHeaderToRead;
                    this._nextColumnHeaderToRead++;
                    if (flag)
                    {
                        this._parser.SkipLongBytes(num, this._stateObj);
                        this._columnDataBytesRemaining = 0L;
                        continue;
                    }
                    if (isNull)
                    {
                        this._parser.GetNullSqlValue(this._data[this._nextColumnDataToRead], col);
                        this._columnDataBytesRemaining = 0L;
                        continue;
                    }
                    this._columnDataBytesRemaining = (long) num;
                    if (i > this._nextColumnDataToRead)
                    {
                        this.ReadColumnData();
                    }
                }
            }
        }
        catch (OutOfMemoryException exception3)
        {
            this._isClosed = true;
            if (this._connection != null)
            {
                this._connection.Abort(exception3);
            }
            throw;
        }
        catch (StackOverflowException exception2)
        {
            this._isClosed = true;
            if (this._connection != null)
            {
                this._connection.Abort(exception2);
            }
            throw;
        }
        catch (ThreadAbortException exception)
        {
            this._isClosed = true;
            if (this._connection != null)
            {
                this._connection.Abort(exception);
            }
            throw;
        }
    }
}

Open in new window


so it's better to assign the result value to some object and use it for null check as well and typecasting.
0
sydneyguyAuthor Commented:
i can understand that there is somethng incorrect about the code and what its reading and how its reding it but still not sure why the try {} statment causes it to opperate correctly

thats whats strang any ideas just on this point???
0
Naman GoelPrinciple Software engineerCommented:
yes, that's really strange, let me also try this on code.
0
Jacques Bourgeois (James Burger)PresidentCommented:
The try does not go into the catch because you do not catch the exception that is happening. There should always be a catch for unexpected exceptions at the end of a try...catch construct:
catch (OutOfMemoryException exception3)
        {
         }
catch (StackOverflowException exception2)
        {
        }
catch (ThreadAbortException exception)
        {
        }
catch
        {
            // Exception that is different than the 3 that were expected
        }

Open in new window

GetString does not handle casts. If the data received by the database is not a String, it won't work. Looks like you are receiving an int, so the right way to get it would be to get the int and then convert it to String.
col = DbReaderLinkedin.GetInt32(i).ToString();

Open in new window

0
Naman GoelPrinciple Software engineerCommented:
for me it is working fine, my code is like this and it is working as expected even with null values in Table1.

using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True"))
            {
                con.Open();

                SqlCommand com = new SqlCommand("select * from Table1", con);
                com.CommandType = System.Data.CommandType.Text;

                SqlDataReader reader = com.ExecuteReader();
                int i = 0;
                while (reader.Read())
                {
                    while (i < reader.VisibleFieldCount)
                    {

                        if (reader.IsDBNull(i)) { }
                        else
                        {
                            string value = reader.GetString(i);
                        }
                        i++;
                    }

                }
            }

Open in new window


my table structure is following:

Name      nvarchar(MAX)
Age              int      
            
 
0
sydneyguyAuthor Commented:
thanks for that got that section going appreciate the help lots of code to work through but at least i am moving forward again thanks for the help got a bit from every bodys input so hope you do not mind me splitting the point thanks for all the help and staying in there with me
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.