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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With