我正在尝试向我的表添加新记录tblEmployee
.这是我的代码:
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();
我在此行收到此错误消息:dRow["Phone"] = txtPhone;
。它说Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'.Couldn't store <System.Web.UI.WebControls.TextBox> in Phone Column. Expected type is Int64.
文本框的代码:
<asp:TextBox ID="txtPhone" runat="server"></asp:TextBox>
我的数据库上Phone
列的数据类型是 int,但我将其更改为 bigint,但仍然收到相同的错误。似乎有什么问题?
顺便说一下,我使用的是 C# ASP.NET。
如果Phone
字段是数字字段,那么您应该:
dRow["Phone"] = Convert.ToInt64(txtPhone.Text);
使用 txtPhone.Text 获取文本框中的值,而不是文本框对象本身。
使用 txtPhone.Text
分配电话号码的值。
试试这个
protected void btnAdd_Click(object sender, EventArgs e) {
cb = new SqlCommandBuilder(daEmp);
DataRow dRow = dsEmp.Tables["tblEmployee"].NewRow();
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;
dRow["DepartmentID"] = drpDepartments.SelectedValue;
dsEmp.Tables["tblEmployee"].Rows.Add(dRow);
daEmp.Update(dsEmp, "tblEmployee");
dsEmp.Tables["tblEmployee"].AcceptChanges();
}
任何地方都使用 .Text
属性,对于电话投射,它是整数
protected void btnAdd_Click(object sender, EventArgs e)
{
cb = new SqlCommandBuilder(daEmp);
DataRow dRow = dsEmp.Tables["tblEmployee"].NewRow();
dRow["Lname"] = txtLname.Text;
dRow["Fname"] = txtFname.Text;
dRow["Mname"] = txtMname.Text;
dRow["Address"] = txtAddress.Text;
dRow["Email"] = txtEmail.Text;
dRow["Phone"] = Convert.ToInt32(txtPhone.Text);
dRow["Jobtitle"] = txtJobtitle.Text;
dRow["Salary"] = txtSalary.Text;
dRow["DepartmentID"] = drpDepartments.SelectedValue;
dsEmp.Tables["tblEmployee"].Rows.Add(dRow);
daEmp.Update(dsEmp, "tblEmployee");
dsEmp.Tables["tblEmployee"].AcceptChanges();
}
只需通过添加txtPhone.text将手机转换为文本即可。实际上,您应该对Web表单中的所有字段值执行此操作,并且还需要对每个表单字段进行适当的验证,这是一种很好的做法。