0

データをデータベースに保存中にエラーが発生しました。DataAdapter.Fill(ds,"Table") は、データ型 nvarchar を数値に変換しているときにエラーを示す 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);
        }
    }
}
4

3 に答える 3

0

txtID.Text整数ではないようです。最初に変換する必要があります。試す:

da.SelectCommand.Parameters.AddWithValue("@ID",Convert.ToInt32(txtID.Text));
于 2013-02-06T14:30:29.640 に答える
0

データベースに文字列として渡し@IDています(データベースの観点からは nvarchar )。コマンド パラメータtxtID.Textを設定するときは、適切な数値にキャスト/変換する必要があります。@ID電話する必要があると思いますint.Parse(txtID.Text)(IDがデータベース内の整数であると仮定します)。

余談ですが、 に無効な ID が入力されないようにする必要がある場合もありますtxtID.Text。このシナリオでは、次を使用できます。

int id;
if (!int.TryParse(txtID.Text, out id))
{
    //an invalid id was supplied so stop processing and warn user
}
于 2013-02-06T14:29:23.897 に答える
0

この行:

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

txtID.Text整数に変換する必要がある文字列です。Int.TryParseを参照してください

于 2013-02-06T14:29:42.357 に答える