Mike Eghtebas
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.
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;
}
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).ToStrin g();
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.
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).ToStrin
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();
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you very much.
e.g.
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.