将文本框中的新记录添加到数据库时出错



将数据保存到数据库时出错。将数据类型nvarchar转换为数字时,DataAdapter.Fill(ds,"Table")正在引发SqlException,并报告错误。

private void btnSave_Click_1(object sender, EventArgs e)
{
    da = new SqlDataAdapter();
    da.SelectCommand = new SqlCommand("select * from Measurement where ID = @ID", con);
    da.SelectCommand.Parameters.AddWithValue("@ID", txtID.Text);
    SqlCommandBuilder cb = new SqlCommandBuilder(da);
    da.Fill(ds, "Measurement"); //(SqlException Unhandled)Error converting data type nvarchar to numeric.
    if (String.IsNullOrEmpty(txtCellNo.Text.Trim()))
    {
        MessageBox.Show("Please enter Cell Number");
    }
    else
    {
        try
        {
            dr = ds.Tables["Measurement"].Rows[0];
            dr["CellNumber"] = txtCellNo.Text.Trim();
            dr["FirstName"] = txtFirstName.Text;
            dr["LastName"] = txtLastName.Text;
            dr["Shirt"] = txtShirt.Text;
            dr["Pant"] = txtPant.Text;
            dr["DueDate"] = txtDueDate.Text;
            dr["Date"] = txtDate.Text;
            cb.GetUpdateCommand();
            da.Update(ds, "Measurement");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

此行:

da.SelectCommand.Parameters.AddWithValue("@ID",txtID.Text);

txtID.Text是一个需要转换为整数的字符串。请参阅Int.TryParse

您将@ID作为字符串传递到数据库(从数据库的角度来看是nvarchar)。设置@ID命令参数时,需要将txtID.Text强制转换为适当的数值。我怀疑您需要调用int.Parse(txtID.Text)(假设ID是数据库中的一个整数)。

另外,您可能还需要防止在txtID.Text中输入无效的id。在这种情况下,您可以使用:

int id;
if (!int.TryParse(txtID.Text, out id))
{
    //an invalid id was supplied so stop processing and warn user
}

看起来txtID.Text可能不是整数。你应该先转换它。尝试:

da.SelectCommand.Parameters.AddWithValue("@ID",Convert.ToInt32(txtID.Text));

最新更新