Hello,I have a problem in my program when I want to insert data into the db.This is my code:
public void SaveData(object param)
{
string connstring = null;
connstring = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\user0909\\Documents\\AttendanceStudents.mdf;Integrated Security=True;Connect Timeout=30";
try
{
using (SqlConnection con = new SqlConnection(connstring))
{
string sql = "Insert into RegisterStudent(SN,sNr,fName,lName,semester)Values(@sn,@studentNr,@fName,@lName,@semester)";
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@SN", SqlDbType.Int).Value = sn;
cmd.Parameters.AddWithValue("@sNr", SqlDbType.Int).Value = studentNr;
cmd.Parameters.AddWithValue("@fName", SqlDbType.NVarChar).Value = fName;
cmd.Parameters.AddWithValue("@lName", SqlDbType.NVarChar).Value = lName;
cmd.Parameters.AddWithValue("@semester", SqlDbType.Int).Value = semester;
if(!string.IsNullOrEmpty(sql))
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I insert all the values in the textboxes,but I get the error"
Must declare variable @studentNr"
This is my table:
CREATE TABLE [dbo].[RegisterStudent]
(
[SN] INT NOT NULL PRIMARY KEY,
[sNr] INT NOT NULL,
[fName] NVARCHAR(MAX) NOT NULL,
[lName] NVARCHAR(MAX) NOT NULL,
[semester] INT NULL
)
What I have tried:
This is what I have tried:
SqlParameter StudentNR = cmd.Parameters.AddWithValue("@sNr", SqlDbType.Int);
cmd.Parameters["@sNr"].Value = studentNr;
if (StudentNR.Value == null)
{
StudentNR.Value = DBNull.Value;
}
I tried this approach,but I still get the error?What could be the problem?Thank you in advance!