选择插入下拉列表值

时间:2013-12-18 00:38:50

标签: c# asp.net sql-server

我已经尝试了我见过的各种代码组合,但无法弄清楚这一点。我想要做的就是插入用户在表单上选择的下拉列表的值。我想将它插入refDepartmentID。下面是我如何填充ddl和实际插入的代码。我没有收到错误,而是在下拉列表中插入具有“selected”属性的第一个ID。它总是“1”,不会插入我选择的那个。 谢谢!

// 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();
   }
}

3 个答案:

答案 0 :(得分:1)

在致电insertNewProject之前,您是否可以检查是否意外重新绑定了列表?否则,您选择的任何值都将丢失,并且将始终返回列表中的第一项SelectedValue

答案 1 :(得分:1)

你没有发布Page_Load方法,但我认为你忘记检查它是否是回发。 Page_Load应如下所示:

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();
        }
    }
}

答案 2 :(得分:0)

你很亲密。要获取ID,您只需执行ddlDepartment.SelectedItem.Value