moe
moe

Reputation: 5249

Conversion failed when converting the varchar value to data type int

I have GridView and inside the gridview i have a hyperlink in witch i am trying to pass a query-string into another page. The ID is an INT type but not sure why i am getting this error:

Conversion failed when converting the varchar value '{0}' to data type int

When i load the detail page by itself without using the hyperlink, it works for me but when i click the hyperlink then i get this error that i mentioned above. Here is my hyper link code:

<asp:TemplateField>
   <ItemTemplate>
      <asp:HyperLink ID="HyperLink2" Text="VIEW DETAIL" runat="server" NavigateUrl= "~/DET/MARKETING.aspx?ID={0}"  Target="_blank">HyperLink</asp:HyperLink>
   </ItemTemplate>
</asp:TemplateField>

Here is the code for the detail page:

protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            string QUEST_SK = Request.QueryString["QUEST_SK"].ToString();
            // string MPost_ID = "773";
            sqlcon.Open();
            sqlcmd = new SqlCommand("SELECT ID, DESC  FROM Table1 WHERE ID= '" + ID+ "'  ", sqlcon);
            da = new SqlDataAdapter(sqlcmd);
            da.Fill(dt);
            sqlcon.Close();
            GridView1.DataSource = dt;
            GridView1.DataBind();
            sqlcon.Close();
        }
    }

Upvotes: 0

Views: 2214

Answers (1)

Ashraf Z. Al-Saqqa
Ashraf Z. Al-Saqqa

Reputation: 30

The Problem in your SQL Statement

protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            string QUEST_SK = Request.QueryString["QUEST_SK"].ToString();
            // string MPost_ID = "773";
            sqlcon.Open();
            sqlcmd = new SqlCommand("SELECT ID, DESC  FROM Table1 WHERE ID= " + ID, sqlcon);
            da = new SqlDataAdapter(sqlcmd);
            da.Fill(dt);
            sqlcon.Close();
            GridView1.DataSource = dt;
            GridView1.DataBind();
            sqlcon.Close();
        }
    }

You Can use Eval

like

<asp:TemplateField>
       <ItemTemplate>
          <asp:HyperLink ID="HyperLink2" Text="VIEW DETAIL" runat="server" NavigateUrl= '<%# Eval("id","~/DET/MARKETING.aspx?ID={0}") %>'  Target="_blank">HyperLink</asp:HyperLink>
       </ItemTemplate>
    </asp:TemplateField>

or

<asp:TemplateField>
   <ItemTemplate>
      <asp:HyperLink ID="HyperLink2" Text="VIEW DETAIL" runat="server" NavigateUrl= '~/DET/MARKETING.aspx?ID=<%# Eval("ID") %>'  Target="_blank">HyperLink</asp:HyperLink>
   </ItemTemplate>
</asp:TemplateField>

Upvotes: 1

Related Questions