kh aafi kh aafi - 1 month ago 6
C# Question

Must Declare a static variable in c# Winfoms

I have got an error that you must have to declare a static variable @campus_id. I don't know how to declare and where to declare and what it means to declare a static variable. Help me please!

private void btnSave_Click(object sender, EventArgs e)
{
try
{
CS = ConfigurationManager
.ConnectionStrings["UMSdbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand(
"SELECT ISNULL(MAX(campus_id),0)+1 FROM Campus", con);
cmd.CommandType = CommandType.Text;
tbCampusID.Text = cmd.ExecuteScalar().ToString();

using (SqlCommand cmd1 = new SqlCommand(
"INSERT INTO Campus (campus_id,campus_name)VALUES(@camp_id,camp_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("@campus_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("@campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Saved");
}
}
}
catch (Exception)
{
}
}

Answer

You are adding value to a placeholder that is not yet defined. see this statement cmd1.Parameters.AddWithValue("@campus_id", tbCampusID.Text); Here you are using campus_id as placeholder and take a look into the insert query, ie., INSERT INTO Campus (campus_id,campus_name)VALUES(@camp_id,camp_name). and there the placeholder is camp_id and that causing the error; use like this:

string querySql = "INSERT INTO Campus (campus_id, campus_name) VALUES(@camp_id, @campus_name)"
using (SqlCommand cmd1 = new SqlCommand(querySql, con))
{
    cmd1.CommandType = CommandType.Text;
    cmd1.Parameters.AddWithValue("@camp_id", tbCampusID.Text);
    cmd1.Parameters.AddWithValue("@campus_name", tbCampusName.Text);
    cmd1.ExecuteNonQuery();
    con.Close();
}
Comments