Link to home
Start Free TrialLog in
Avatar of sydneyguy
sydneyguyFlag for Australia

asked on

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); }


                               
   

                               
 
 




Avatar of Bill Nolan
Bill Nolan
Flag of United States of America image

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.
ASKER CERTIFIED SOLUTION
Avatar of Naman Goel
Naman Goel
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sydneyguy

ASKER

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

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.
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




 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
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
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
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???
yes, that's really strange, let me also try this on code.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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      
            
 
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