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