简体   繁体   English

选择插入下拉列表值

[英]Insert dropdownlist value selected

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. 我想将它插入refDepartmentID。 Below is the code for how I populate the ddl and the actual insert. 下面是我如何填充ddl和实际插入的代码。 I'm not getting an error, but instead it's inserting the first ID in the dropdown list which has the "selected" attribute. 我没有收到错误,而是在下拉列表中插入具有“selected”属性的第一个ID。 It's always "1" and won't insert the one I'm choosing. 它总是“1”,不会插入我选择的那个。 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();
   }
}

Can you check that you're not accidentally re-binding the list before your call to insertNewProject ? 在调用insertNewProject之前,您是否可以检查是否意外重新绑定了列表? Otherwise whatever value you've chosen will be lost and it will always be returning the first item in the list as SelectedValue 否则任何值你所选择将丢失,它总是会在列表中被返回的第一个项目SelectedValue

You've not posted the Page_Load method but I think you are forgetting to check if it's postback or not. 你没有发布Page_Load方法,但我认为你忘记检查它是否是回发。 Page_Load should look like this: 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();
        }
    }
}

You're close. 你很亲密 To get the ID you just need to do ddlDepartment.SelectedItem.Value 要获取ID,您只需要执行ddlDepartment.SelectedItem.Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM