I'm trying to make a Student Management System using ASP.NET webforms and a database. I've linked database with my project using Entity Framework.
But after I've clicked the "Submit" button, I get a foreign key error.
Here is my code and database diagram:
public void btnAddStudent_Click(object sender, EventArgs e)
{
var db = new STUDENT_MANAGEEntities();
var tb = new Student_Info();
tb.Student_Id = Convert.ToInt32(txtStudentId.Text.Trim());
tb.Name = txtName.Text.Trim();
tb.Semester_Id = Convert.ToInt32(dpdSemester.SelectedIndex);
tb.Session = txtSession.Text.Trim();
tb.Department_Id = Convert.ToInt32(dpdDepartment.SelectedIndex);
tb.Shift_Id = Convert.ToInt32(dpdShift.SelectedIndex);
tb.Gender_Id = Convert.ToInt32(dpdGender.SelectedIndex);
tb.Blood_Id = Convert.ToInt32(dpdBlood.SelectedIndex);
tb.Birth_Date = clrBirthDate.SelectedDate;
tb.Contact = txtContact.Text.Trim();
tb.Address = txtAddress.Text.Trim();
db.AddToStudent_Info(tb);
db.SaveChanges();
}
And this is the error I get:
CodePudding user response:
The issue is that you are using the SelectedIndex
and using that for the FK. SelectedIndex
is just the position in the list of items that was selected, so 0,1,2,3,4,... The values in your drop down likely have different ID values, and you may even have them sorted by name etc. so the IDs might be 4,1,2,5,3 for example. Selecting the first item in the list might be Blood ID 4, but it's SelectedIndex
would be 0 which doesn't correspond to any Blood record.
When you populate your Comboboxes based on the lookup tables you need to bind both the Text, and the Value of each item. Value being the Key for that record, I.e. BloodTypeId. Then I believe the SelectedValue
should give you that bound Value amount, otherwise you might need to cast SelectedItem
as a SelectListItem
and get it's Value
:
// try this...
tb.Blood_Id = Convert.ToInt32(dpdBlood.SelectedValue);
// or this...
var selectedItem = (SelectListItem)dpdBlood.SelectedItem;
tb.Blood_Id = Convert.ToInt32(selectedItem.Value);
This should be done for all drop-downs. Otherwise you will get situations where the values you select don't get saved to the same record (where the index <> the ID) or errors where index doesn't match any ID.