将nvarchar值转换为数据类型int时,转换失败

本文关键字:转换 失败 int nvarchar 数据类型 | 更新日期: 2023-09-27 18:09:51

这里的错误是什么?我得到了一个错误。但是lblStage得到stage值。但是错误来了。

try
{
    SqlCommand cmd = new SqlCommand("Select distinct (stage) from tblStatus where EstimateID=@EstimateID", con);
    cmd.Parameters.AddWithValue("EstimateID", listEstimateID.Text);
    lblStage.Text = cmd.ExecuteScalar().ToString();
}
catch (Exception exc)
{
    MessageBox.Show(exc.Message);
}

将nvarchar值转换为数据类型int时,转换失败

创建一个全局参数并将其设置为false。Bool = false;

在表单load使它为真Isloaded = true;

    private void listEstimateID_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (isloaded)
            {
                SqlCommand cmd = new SqlCommand("Select distinct (stage) from tblStatus where EstimateID=@EstimateID", con);
                cmd.Parameters.AddWithValue("EstimateID", Convert.ToInt32(listEstimateID.Text));
                lblStage.Text = cmd.ExecuteScalar().ToString(); 
            }
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
    }
try
{
    SqlCommand cmd = new SqlCommand("Select distinct (stage) from tblStatus where EstimateID=@EstimateID", con);
    int id;
    if(int.TryParse(listEstimateID.Text, out id)
    {
        cmd.Parameters.AddWithValue("EstimateID", id );
    }
    else  MessageBox.Show("Invalid Estimate ID");
    lblStage.Text = cmd.ExecuteScalar().ToString();
}
catch (Exception exc)
{
    MessageBox.Show(exc.Message);
}

当您为参数添加值时,cmd.Parameters.AddWithValue中应该有@ParameterName

try
{
    SqlCommand cmd = new SqlCommand("Select distinct (stage) from tblStatus where EstimateID=@EstimateID", con);
    cmd.Parameters.AddWithValue("@EstimateID", Convert.ToInt32(listEstimateID.Text));
    lblStage.Text = cmd.ExecuteScalar().ToString();
}
catch (Exception exc)
{
    MessageBox.Show(exc.Message);
}