I am trying to store the result from my SQL query into a string variable. This is what I have:
string strName = dt.Rows[i][name].ToString();
string selectBrandID = "SELECT [Brand_ID] FROM [myTable] WHERE [real_name] = '" + strName + "'";
using (SqlCommand sqlCmdSelectBrandID = new SqlCommand(selectBrandID, sqlConn))
{
sqlCmdSelectBrandID .Connection.Open();
using (SqlDataReader reader = sqlCmdSelectBrandID.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
string newBrandID = reader.GetString(reader.GetOrdinal("Brand_ID"));
}
sqlCmdSelectBrandID.Connection.Close();
}
}
This currently throws the exception Unable to cast object of type 'System.Int32' to type 'System.String'. On string newBrandID =reader.GetString(reader.GetOrdinal("Brand_ID")); line.
Any advice on how to fix this?