Link to home
Start Free TrialLog in
Avatar of Mike Eghtebas
Mike EghtebasFlag for United States of America

asked on

Unable to cast object type 'Syatem.Int32' to type .System.String'.

Here, I am reading values from a table. Reading int type fields give me problem.

At line 14, I am getting error stating: "Unable to cast object type 'Syatem.Int32' to type .System.String'."

Question: How can I handle this.

Thank you.
public string ReadCriteria(string dataPoint)
    {
        string criteria = "";
        using (cn = SetConnection())
        {
            command.CommandText = "SELECT Top 1 [" + dataPoint + "] From RodCtiteria";
            command.CommandType = CommandType.Text;
            cn.Open();
            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                reader.Read();
                if (!reader.IsDBNull(0)) // instead of: reader.GetString(0) != "" MetricIdL
                    criteria = reader.GetString(0);   //*********************< error here
            }
            reader.Close();
        }
        return criteria;
    }

Open in new window

Avatar of kaufmed
kaufmed
Flag of United States of America image

The data type of the data in the reader is of type int, so you cannot use GetString. You have to use the method that is appropriate for that data type:  GetInt32.

e.g.

criteria = reader.GetInt32(0).ToString();

Open in new window


Though you do want to ensure that you won't be getting nulls back from the database. If that be the case, then the logic will need to be tweaked.
Avatar of Mike Eghtebas

ASKER

kaufmed,

Thank you for the solution. The values to be read are often string but sometimes int.

I suppose I need to add error handling here to handle both sting and int values to be read.

Question: If error handling is the way to go, could you please give me the syntax for it.

Later, I will learn about error handling to code it myself but at this point I could use some help.

If error handling is not necessary please add some comment on how would it work. I will try

criteria = reader.GetInt32(0).ToString();

to read both string and int values to see how it goes.

Regards,

Mike

Test Result:
Now I am getting "Specified cast is not valid." (in the case of string data of course).

It seems the following work, but the block is not complete.
try
                    {
                        criteria = reader.GetString(0);
                    }
                    catch
                    {
                   // }
                  //  finally
                   // {
                        criteria = reader.GetInt32(0).ToString();
                    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America 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
Thank you very much.