1
con.Open();
cmd = new SqlCommand("USE PRODUCTS SELECT BOUGHT FROM " +
                     DropDownList1.SelectedItem.Text +
                     " WHERE ID = @ID", con);
cmd.Parameters.Add("ID", SqlDbType.Int).Value = DropDownList2.SelectedIndex;
int i = cmd.ExecuteReader().GetInt32(0);
con.Close();

I can't read integer values with reader like this. I get runtime error System.InvalidOperationException. What is wrong with my code ? if you can't find the mistake, can you explain how can i read integer values with reader ? By the way this part of code gives the error:

int i = cmd.ExecuteReader().GetInt32(0);
0

3 Answers 3

1

Try this:

int x=0;
using (
SqlConnection connection = new SqlConnection(strCon))
{
    SqlCommand command = new SqlCommand(sql_string, connection);
    connection.Open();
    DataReader reader = command.ExecuteReader();
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            x = reader.GetInt32(0);
        }
    } 

    reader.Close();
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to initialise a reader and then read it

using (SqlDataReader rdr = cmd.ExecuteReader())
{
  while (rdr.Read()) // or just rdr.Read() if you know only one row is returned
  {
    int i = rdr.GetInt32(0);

Comments

0

What I have done to make things a lot easier on my end, since I mainly use SQL all over the place, is make some extensions.

eg

public static Int32 GetInt32(this SqlDataReader rdr, string column)
{
     return Convert.ToInt32(rdr[column]);
}

Comments

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.