LALBABU
LALBABU

Reputation: 19

Conversion failed when converting the nvarchar value 'A' to data type int

Conversion failed when converting the nvarchar value 'A' to data type int.

private void linksdetail(string id)
{
    SqlConnection con = new SqlConnection(con_string);
    con.Open();

    SqlCommand cmd = new SqlCommand(" select a.solution_title,b.solution_sub_id,b.solutions_id,a.url from cms_solution_viewnew a, cms_solution_viewnew b where a.row_id = b.solution_sub_id  and b.solutions_id='" + id + "'", con);

    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.Read())
    {

        HyperLink1.Text = dr["solution_title"].ToString();

        HyperLink1.NavigateUrl = dr["url"].ToString();

    }
    dr.Close();
    con.Close();
}

How to solve it please help me.

Upvotes: 1

Views: 2987

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98850

solutions_id column data type is integer type and value of id is 9

Error message is pretty self explanatory. You try to assign sequence of characters to int typed column. Based on your example values, you don't need to use single quotes with your numeric columns. You can change your

b.solutions_id = '" + id + "'"

to

b.solutions_id = " + id

but as a better way, use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader automatically instead of calling Close methods manually.

using(var con = new SqlConnection(con_string))
using(var cmd = con.CreateCommand())
{
    cmd.CommandText = "select a.solution_title,b.solution_sub_id,b.solutions_id,a.url from cms_solution_viewnew a, cms_solution_viewnew b where a.row_id = b.solution_sub_id  and b.solutions_id = @id";
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    con.Open();
    using(var dr = cmd.ExecuteReader())
    {
        // Do your stuff
    }
}

Upvotes: 1

Related Questions