Reputation: 658
I've tried every combination of code from examples I've seen but can't figure this out. All I want to do is insert the value of the dropdownlist the user selects on the form. I want to insert it into refDepartmentID. Below is the code for how I populate the ddl and the actual insert. I'm not getting an error, but instead it's inserting the first ID in the dropdown list which has the "selected" attribute. It's always "1" and won't insert the one I'm choosing. Thanks!
// populates Departments dropdownlist
using (dbOrganizationEntities1 myEntities = new dbOrganizationEntities1())
{
var allDepartments = from tbDepartments in myEntities.tbDepartments
select tbDepartments;
ddlDepartments.DataSource = allDepartments;
ddlDepartments.DataValueField = "DepartmentID";
ddlDepartments.DataTextField = "DepartmentName";
ddlDepartments.DataBind();
}
protected void btnRequest_Click(object sender, EventArgs e)
{
insertNewProject();
}
private void insertNewProject()
{
using (dbPSREntities1 context = new dbPSREntities1())
{
//Create a new instance of the Customer object
tbProject proj = new tbProject { //Add new values to each fields
ProjectContactInfo = txtContactPhone.Text, //trying to insert this
refDepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue) };
context.tbProjects.AddObject(proj);
context.SaveChanges();
}
}
Upvotes: 0
Views: 116
Reputation: 58
You've not posted the Page_Load method but I think you are forgetting to check if it's postback or not. Page_Load should look like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// populates Departments dropdownlist
using (dbOrganizationEntities1 myEntities = new dbOrganizationEntities1())
{
var allDepartments = from tbDepartments in myEntities.tbDepartments
select tbDepartments;
ddlDepartments.DataSource = allDepartments;
ddlDepartments.DataValueField = "DepartmentID";
ddlDepartments.DataTextField = "DepartmentName";
ddlDepartments.DataBind();
}
}
}
Upvotes: 1
Reputation: 1874
Can you check that you're not accidentally re-binding the list before your call to insertNewProject
? Otherwise whatever value you've chosen will be lost and it will always be returning the first item in the list as SelectedValue
Upvotes: 1
Reputation: 599
You're close. To get the ID you just need to do ddlDepartment.SelectedItem.Value
Upvotes: 0