I have a web page and there I have fields to hold some data.
One of the fields holds the IDs and names of students enrolled in a particular course. I want to be able to enroll new students to the course using a drop-down list. If the item selected in the drop-down list already exists in the Courses Table, I should display an error message.
I have a code to do these but when I select an already existing value in the drop-down list it doesn't show an error message. It assumes it's a new value and throws an exception because the Database doesn't accept duplicate records.
How can I solve this problem?
I use c# language to design this web page in ASP.NET.
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True");
string qs = Request.QueryString["id"];
// Variable qs Keeps CourseID retrieved from query string
string sv = DropDownList1.SelectedItem.Value;
// Variable sv keeps selected value from DropDownList
SqlCommand cmd = new SqlCommand("Select * from Enrolment as e, Students as s where e.StudentID = s.StudentID and " +
"CourseID = " + qs + " and StudentName = '" + sv +"'", con);
// There are Students, Courses, and Enrolment tables in database
// Students table columns are StudentID, StudentName, BirthDate
// Course table columns are CourseID, CourseCode, CourseName, Instructor
// Enrolment table columns are CourseID and StudentID
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows)
{
Label1.Visible = true;
Label1.Text = "The selected student is already registered to the course!";
Label1.ForeColor = Color.Red;
}
else
{
Label1.Visible = true;
Label1.Text = "The selected student is succesfully registered!";
Label1.ForeColor = Color.Green;
SqlDataSource4.Insert();
GridView1.DataBind();
}
reader.Close();
con.Close();
}
When i select a name from DropDownList which is not exist in Database, i get proper result.
For example, Think about "Jeff Bezos" is already registered for given course. When i choose "Jeff Bezos" i should get error message but I get exception which says that is duplicate.