InvalidOperationExeption was unhandled by user code

Am new to C#. Guys help me out.
The error i got:

An exception of type ‘System.InvalidOperationException’ occurred in System.Data.dll but was not handled in user code

protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
            conn.Open();

            String showInventories = "SELECT * FROM tbl_inventories";
            SqlCommand cmd = new SqlCommand(showInventories, conn);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            SqlDataReader dr = cmd.ExecuteReader();

            String qCount = "SELECT COUNT(*) FROM tbl_inventories";
            cmd.CommandText = "SELECT COUNT(*) FROM tbl_inventories";
            Int32 count = cmd.ExecuteNonQuery();            
            dr.Close();
        }

i want to store the count query to count variable.

Thank you for providing the exact error message. That helps us help you. However you did not tell us what line the error is occurring. It helps to also provide that.

I will assume that the exception is occurring on the SqlConnection.Open call. Look at the SqlConnection.Open Method documentation. It says that an InvalidOperationException can occur if there is not a data source or server. So if the error is occurring there then there is a problem with your ConnectionString. Something I might do is to change the SqlConnection constructor to something such as:

string s = ConfigurationManager.ConnectionStrings["conn"].ToString();
SqlConnection conn = new SqlConnection(s);
conn.Open();

And then in the debugger I can look at what the string actually is. My guess is that it is empty. Do you know how to use breakpoints?

1 Like

Check if ConfigurationManager.ConnectionStrings[“conn”].ToString() is returning any value.

string con = ConfigurationManager.ConnectionStrings[“conn”].ToString();