1

While trying to pass an integer parameter @id to a stored procedure, I get an error da.Fill(ds):

Additional information: Conversion failed when converting the varchar value '@id' to data type int.

I have made sure that integer value is passed and stored procedure contain the correct datatype. What other possibilities are there to rectify this error?

SqlConnection conn = new SqlConnection(cs);
conn.Open(); 

SqlCommand cmd1 = new SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("@id", id);

SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
3
  • why would a parameter that ends in "Id" be a varchar? Commented Apr 16, 2018 at 11:42
  • It seems the column id on your table is a varchar Commented Apr 16, 2018 at 11:43
  • 1
    Looks like the c# variable id is a string. Commented Apr 16, 2018 at 11:44

2 Answers 2

0

If you know better, do not use AddWithValue() ... it has to "guess" what datatype you have in your DB based on what you put into the command. It is errorprone and causes unneeded conversions to take place.

Also: use using(..) around disposables, especially when using Database-access as it will close your connections even if exceptions arise - not using using might let some connection stay unclosed.

DataSet ds = new DataSet ();
using (var conn = new SqlConnection (cs))
{
    using (var cmd1 = new SqlCommand ("asp_GetTrainingDetail", conn))
    {
        cmd1.CommandType = CommandType.StoredProcedure;
        cmd1.Parameters.Add("@id", System.Data.SqlDbType.BigInt).Value = id;

        using (var da = new SqlDataAdapter (cmd1))
        {
            da.Fill (ds);
        }
    }
}

Read the link in do not use AddWithValue() for more background infos.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this...

 SqlConnection conn = new SqlConnection(cs);
        conn.Open(); SqlCommand cmd1 = new 
        SqlCommand("asp_GetTrainingDetail", conn);
        cmd1.CommandType = CommandType.StoredProcedure;
        cmd1.Parameters.AddWithValue("@id", Int.Parse(id));
        SqlDataAdapter da = new SqlDataAdapter(cmd1);
        DataSet ds = new DataSet();
        da.Fill(ds);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.