Lalindra Kawshika
Lalindra Kawshika

Reputation: 313

Conversion failed when converting nvarchar value to data type int

What is the error here? I got an error. but lblStage get the stage value. But error comes.

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);
}

Upvotes: 0

Views: 1463

Answers (3)

Lalindra Kawshika
Lalindra Kawshika

Reputation: 313

Make a global parameter and set it false. bool isloaded = false;

In the form load make it true 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);
        }
    }

Upvotes: 2

Sailesh Babu Doppalapudi
Sailesh Babu Doppalapudi

Reputation: 1536

When you are adding values for parameters, there should be @ParameterName in cmd.Parameters.AddWithValue

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);
}

See if this works.

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 16966

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);
}

Upvotes: 0

Related Questions