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

C# 将文本框中的新记录添加到数据库时出错,c#,winforms,C#,Winforms,将数据保存到数据库时出错。在将数据类型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 =

将数据保存到数据库时出错。在将数据类型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);
        }
    }
}

您正在将
@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
}
这一行:

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

txtID.Text
是需要转换为整数的字符串。请参见它看起来像
txtID。Text
可能不是整数。你应该先转换它。尝试:

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

我想你不再需要我的帮助了,很多专业人士都在回答你的问题:)@AbZy现在的问题是找不到dr=ds.Tables[“Measurement”].Rows[0]。它说第0行没有位置。我按照你的指示做了,只是看到你用一种叫做
btnSave\u Click\u 1
的方法来执行数据库操作,我的眼睛就痛了。一旦我掌握了这个主题,我就可以研究n层体系结构;)@KiritiK不能为新行处理相同的代码。你需要像问第一个问题之前那样做。通过创建一个新行。Int.TryParse工作得很有魅力!谢谢LarsTech