Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must declare the scalar variable in C#

I am developing an app in C# in which when I am interacting with my database SQL Server it is giving me the exception of 'Must declare the Scalar Variable'. The code is following

public DataTable Search(string clas)
{
    try
    {
        DataTable table = new DataTable();
        string query = "";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            if (clas != "")
            {
                query = "Select * from StudentManagement Where classEnrolled=@cls";
                //dataAdapter
                dataAdapter = new SqlDataAdapter(query, connectionString);
                dataAdapter.SelectCommand.Parameters.Add(new SqlParameter("cls", clas));
            }

            dataAdapter = new SqlDataAdapter(query, connectionString);
            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand. These are used to
            // update the database.
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            // Populate a new data table and bind it to the BindingSource.
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
        }
        return table;
    }
    catch (Exception e)
    {
        return null;
    }    
}

Please help me

like image 628
Billz Avatar asked Dec 12 '25 20:12

Billz


1 Answers

I have a strong suspicion that clas is a null reference. Note that this will still trigger your != "" branch, since a null-reference is not the same as an empty string.

Maybe use:

if(!string.IsNullOrEmpty(clas)) {...}

Instead?

A peculiarity of db-parameters is that they are not included if the .Value is null. Check the value you are sending in.

It doesn't apply in your case (since in normal SQL nothing ever equals NULL) but: if you intend to send NULL as a parameter, you must set the value to DBNull.Value instead.

like image 53
Marc Gravell Avatar answered Dec 14 '25 10:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!