我正在尝试使用 C# ASP.NET 更新记录。我有以下表格和文本框。该过程将首先搜索 EmployeeID。输入EmployeeID
on txtID 并点击 btnSearch
。文本框将由 的值填充EmployeeID = txtID.Text
。txtLname
, txtFname
, 等将被填充。要保存更改,请点击btnUpdate
。
但是每当我尝试单击下拉框来更改员工的部门时,都没有错误,但没有保存更改。此外,当我尝试更改 EmployeeID 时,它会返回此错误:Object reference not set to an instance of an object
on this line dRow["EmployeeID"] = txtID.Text;
。
EmployeeID 和 DeptID 都设置为主键
这是我的 btnSearch_Click() 代码
DataRow myRow = dsEmp.Tables["tblEmployee"].Rows.Find(int.Parse(txtID.Text));
txtID.Text = myRow["EmployeeID"].ToString();
txtLname.Text = myRow["Lname"].ToString();
txtFname.Text = myRow["Fname"].ToString();
txtMname.Text = myRow["Mname"].ToString();
txtAddress.Text = myRow["Address"].ToString();
txtEmail.Text = myRow["Email"].ToString();
txtPhone.Text = myRow["Phone"].ToString();
txtJobtitle.Text = myRow["Jobtitle"].ToString();
txtSalary.Text = myRow["Salary"].ToString();
drpDepartments.SelectedValue = myRow["DeptID"].ToString();`
这是我的 btnUpdate_click() 代码
cb = new SqlCommandBuilder(daEmp);
DataRow dRow = dsEmp.Tables["tblEmployee"].Rows.Find(int.Parse(txtID.Text));
dRow["EmployeeID"] = txtID.Text;
dRow["DeptID"] = drpDepartments.SelectedValue;
dRow["Lname"] = txtLname.Text;
dRow["Fname"] = txtFname.Text;
dRow["Mname"] = txtMname.Text;
dRow["Address"] = txtAddress.Text;
dRow["Email"] = txtEmail.Text;
dRow["Phone"] = txtPhone.Text;
dRow["Jobtitle"] = txtJobtitle.Text;
dRow["Salary"] = txtSalary.Text;
daEmp.Update(dsEmp, "tblEmployee");
dsEmp.Tables["tblEmployee"].AcceptChanges();
这是 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();
我只是不明白为什么会这样。请帮助我,我是 ASP.NET 的新手。谢谢。