0

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?

1 Answer 1

2

If your Brand_ID is stored in an integer field, then you should keep it as an integer. The GetString fails because the underlying field is not a string, you could simply use the GetInt32 (see the SqlDataReader docs)

int newBrandID = reader.GetInt32(reader.GetOrdinal("Brand_ID"));

Then, if for whatever purpose you want it as a string, it is just a matter to apply the ToString() method to your integer

string brandID = newBrandID.ToString();
Sign up to request clarification or add additional context in comments.

6 Comments

Ok, so now it is stored and then I just tried to use the variable in an insert statement to place in a sql table and it says "newBrandID doesn't exist in the current context". How can I make that global?
Could you simply return it from this code and pass to the other method? Globals are always a necessary evil. If you could avoid them.... otherwise just declare the newBrandID at the class level
Or, if the insert is following this same block of code, move the declaration of newBrandID at the same level of the strName
Can you show me an example of what you're talking about exactly in your answer?
Weird thing is, is that they are in the same IF statement
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.