0

我有一个网络表单,管理员将在其中向数据库添加新记录。该表单有 1 个下拉drpDepartments框和一些文本框EmployeeID, Fname, Lname等。我可以添加一条新记录,但从下拉框中选择的选项没有改变。它始终是第一个值。这里是表格tblEmployeetblDepartment

在此处输入图像描述 这是我的Page_Load()代码:

            sConn = new SqlConnection(sStr);
            daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
            daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
            dsEmp = new DataSet();
            dsDep = new DataSet();

            daEmp.Fill(dsEmp, "tblEmployee");
            daDep.Fill(dsDep, "tblDepartment");

            dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };

            drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
            drpDepartments.DataTextField = "Description";
            drpDepartments.DataValueField = "DeptID";
            drpDepartments.DataBind();

btnAdd_Click()代码:

       cb = new SqlCommandBuilder(daEmp);

        DataRow dRow = dsEmp.Tables["tblEmployee"].NewRow();
        dRow["EmployeeID"] = txtID.Text;
        dRow["Lname"] = txtLname.Text;
        dRow["Fname"] = txtFname.Text;
        dRow["Mname"] = txtMname.Text;
        dRow["Address"] = txtAddress.Text;
        dRow["Email"] = txtEmail.Text;
        dRow["Phone"] = Convert.ToInt64(txtPhone.Text);
        dRow["Jobtitle"] = txtJobtitle.Text;
        dRow["Salary"] = txtSalary.Text;
        dRow["DeptID"] = drpDepartments.SelectedValue;

        dsEmp.Tables["tblEmployee"].Rows.Add(dRow);
        daEmp.Update(dsEmp, "tblEmployee");
        dsEmp.Tables["tblEmployee"].AcceptChanges();

        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "test", "<script>alert('New record added!');</script>");
        Refresh();
4

1 回答 1

3

下拉列表的绑定只能在!IsPostBack

if(!IsPostBack)
{
 drpDepartments.DataSource = dsDep.Tables["tblDepartment"];// Set DataSource Table First
        drpDepartments.DataTextField = "Department";// Set Column Name of DataTable to set as Text Field
        drpDepartments.DataValueField = "DepartmentID";// Set Column Name of DataTable to set as Value Field
        drpDepartments.DataBind();
}

如果在 postback 事件中绑定 DropDownList,则下拉列表将在 button_click(在 page_load 中)事件中重新绑定,并且用户设置的值将丢失。

于 2013-11-15T03:54:16.520 回答