ket0ma ket0ma - 10 days ago 5
SQL Question

Must declare the scalar variable @ID. eventhought it is already declared

public void loadPanel1()
{
cn.Open();

sqlquery = "SELECT PersonenlisteID From Termin WHERE ID LIKE @ID";
cmd.Parameters.Add("@ID", SqlDbType.NVarChar, 100).Value = selectedID;
cmd = new SqlCommand(sqlquery, cn);
object resultID = cmd.ExecuteScalar(); cn.Close();
}


ERROR : Must declare the scalar variable @ID.

Why is it an error? i do declare it?

Answer

Well this is the result of having global variables around. You have a cmd variable declared at global level and initialized somewhere in your code before this point. As a result you don't get an error message at compile time but only when your code reaches that point.

The global variable receives the new parameter, but the following line reinitializes everything and you loose the parameter.

As said there is no point in having global variables both for command and connections

public void loadPanel1()
{
    string sqlquery = "SELECT PersonenlisteID From Termin WHERE ID LIKE @ID";
    using(SqlConnection cn = new SqlConnection(connectionstring))
    using(SqlCommand cmd = new SqlCommand(sqlquery, cn))
    {
         cn.Open();
         cmd.Parameters.Add("@ID", SqlDbType.NVarChar, 100).Value = selectedID;
         object resultID = cmd.ExecuteScalar();
         .... code that works or return the resultID ...
    }
}

In this way, the connection is correctly closed and disposed at the end of the procedure (released to the connection pool where it can be reused) and you can remove all these pesky global variables and checks on the state of the connection