locked
Gridview sender as link button Input string was not in a correct format RRS feed

  • Question

  • User181930479 posted

    im populating a gridview from code behind and biding fields , them im filtering the gridview with jquery and its working great , but i have a column in gridview that allows the user to download the file ,

    The download action is called also in code behind , but when i click on it im gettinf : sender as link button Input string was not in a correct format

    below is my code :

    aspx:

    <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
            runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound">
            <Columns>
                <asp:BoundField DataField="id" HeaderText="Id" ItemStyle-Width="30" />
                <asp:BoundField DataField="Subject" HeaderText="Subject" ItemStyle-Width="100" />
                <asp:BoundField DataField="SelectSource" HeaderText="SelectSource" ItemStyle-Width="100" />
                <asp:BoundField DataField="SourceName" HeaderText="Source Name" ItemStyle-Width="100" />
    
                <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Operation">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkDownload"   runat="server" Text=" Download" OnClick="DownloadFile"
                                CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
                        </ItemTemplate>
    
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
                    </asp:TemplateField>
    
    
            </Columns>
        </asp:GridView>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript" src="quicksearch.js"></script>
        <script type="text/javascript">
            $(function () {
                $('.search_textbox').each(function (i) {
                    $(this).quicksearch("[id*=GridView1] tr:not(:has(th))", {
                        'testQuery': function (query, txt, row) {
                            return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
                        }
                    });
                });
            });
        </script>

    ASPX.CS

       protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
    
    
        private void BindGrid()
        {
    
            string constr = ConfigurationManager.ConnectionStrings["AIO"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmdinternal = new SqlCommand())
                {
                    cmdinternal.CommandText = "SELECT id, SourceName, SelectSource , Subject from tbl_requestPrintGOV ";
                    cmdinternal.Connection = con;
                    con.Open();
                    GridView1.DataSource = cmdinternal.ExecuteReader();
                    GridView1.DataBind();
                    con.Close();
                }
            }
        }
    
        protected void OnDataBound(object sender, EventArgs e)
        {
            GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
            for (int i = 0; i < GridView1.Columns.Count; i++)
            {
                TableHeaderCell cell = new TableHeaderCell();
                TextBox txtSearch = new TextBox();
                txtSearch.Attributes["placeholder"] = GridView1.Columns[i].HeaderText;
                txtSearch.CssClass = "search_textbox";
                cell.Controls.Add(txtSearch);
                row.Controls.Add(cell);
            }
            GridView1.HeaderRow.Parent.Controls.AddAt(1, row);
        }
    
    
        protected void DownloadFile(object sender, EventArgs e)
        {
            
            int id = int.Parse((sender as LinkButton).CommandArgument);
            byte[] bytes;
            string fileName, contentType;
            string constr = ConfigurationManager.ConnectionStrings["AIO"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmdinternal = new SqlCommand())
                {
                    cmdinternal.CommandText = "select Name, Data, ContentType from tbl_requestPrintGOV where Id=@Id ";
                    cmdinternal.Parameters.AddWithValue("@Id", id);
                    cmdinternal.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmdinternal.ExecuteReader())
                    {
                        sdr.Read();
                        bytes = (byte[])sdr["Data"];
                        contentType = sdr["ContentType"].ToString();
                        fileName = sdr["Name"].ToString();
                    }
                    con.Close();
                }
            }
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = contentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }

    Any help please ???

    Wednesday, July 4, 2018 6:08 AM

All replies

  • User-1171043462 posted

    That could be because the QuickSearch is modifying the GridView HTML.
    What you can do is:
    1. Add a HiddenField below GridView 'hfId'
    2. When DownLoad linkButton is clicked, stored ID in HiddenField
    3. Then in the Server Side Click event get the ID from theHiddenField.

    <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
            runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound">
            <Columns>
                <asp:BoundField DataField="id" HeaderText="Id" ItemStyle-Width="30" />
                <asp:BoundField DataField="Subject" HeaderText="Subject" ItemStyle-Width="100" />
                <asp:BoundField DataField="SelectSource" HeaderText="SelectSource" ItemStyle-Width="100" />
                <asp:BoundField DataField="SourceName" HeaderText="Source Name" ItemStyle-Width="100" />
    
                <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Operation">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkDownload"   runat="server" Text=" Download" OnClick="DownloadFile"
                                CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
                        </ItemTemplate>
    		  <ItemStyle HorizontalAlign="Center"></ItemStyle>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:HiddenField Id = "hfId" runat = "server" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript" src="quicksearch.js"></script>
        <script type="text/javascript">
            $(function () {
    	    $("[id*lnkDownload=]").click(function(){
    		var id = $(this).closest("tr").find("td").eq(0).html();
    		$("[id*=hfId]").val(id);
    	    });
                $('.search_textbox').each(function (i) {
                    $(this).quicksearch("[id*=GridView1] tr:not(:has(th))", {
                        'testQuery': function (query, txt, row) {
                            return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
                        }
                    });
                });
            });
        </script>
    

    On Server Side

    protected void DownloadFile(object sender, EventArgs e)
        {
            
            //int id = int.Parse((sender as LinkButton).CommandArgument);
    	int id = int.Parse(Request.Form[hfId.UniqueID]);
            byte[] bytes;
            string fileName, contentType;
            string constr = ConfigurationManager.ConnectionStrings["AIO"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmdinternal = new SqlCommand())
                {
                    cmdinternal.CommandText = "select Name, Data, ContentType from tbl_requestPrintGOV where Id=@Id ";
                    cmdinternal.Parameters.AddWithValue("@Id", id);
                    cmdinternal.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmdinternal.ExecuteReader())
                    {
                        sdr.Read();
                        bytes = (byte[])sdr["Data"];
                        contentType = sdr["ContentType"].ToString();
                        fileName = sdr["Name"].ToString();
                    }
                    con.Close();
                }
            }
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = contentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }




    Wednesday, July 4, 2018 6:41 PM
  • User181930479 posted

    Dear Friend , 

    its a honor having you replying to my thread , i have tried your suggestion still getting the same problem and now i can not filter the gridview anymore.

    Thursday, July 5, 2018 4:35 AM
  • User283571144 posted

    Hi NAF,

    According to your descritpion and codes, I found you used onclick event to fired the DownloadFile event in code-behind.

    This will make the CommandArgument be null in girdview.

    I suggest you could modify the OnClick to OnCommand, then it will work well.

    More details, you could refer to below codes:

    Notice: I found you add a headline in the databound event, this will make the command value minus one, so I plus one in the code-behind.

    ASPX:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridviewWithQuickSearch.aspx.cs" Inherits="AspNetNormalIssue.Webform.GridviewWithQuickSearch" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
                    runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound">
                    <Columns>
                        <asp:BoundField DataField="id" HeaderText="Id" ItemStyle-Width="30" />
                        <asp:BoundField DataField="Subject" HeaderText="Subject" ItemStyle-Width="100" />
                        <asp:BoundField DataField="SelectSource" HeaderText="SelectSource" ItemStyle-Width="100" />
                        <asp:BoundField DataField="SourceName" HeaderText="Source Name" ItemStyle-Width="100" />
    
                        <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Operation">
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkDownload" runat="server" Text="Download"  OnCommand="DownloadFile"
                                    CommandArgument='<%# Eval("Id")   %>'></asp:LinkButton>
                            </ItemTemplate>  
                            <ItemStyle HorizontalAlign="Center"></ItemStyle>
                        </asp:TemplateField>
    
                    </Columns>
                </asp:GridView>
    
                <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
                <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.quicksearch/2.4.0/jquery.quicksearch.js"></script>
                <script type="text/javascript">
            $(function () {
                $('.search_textbox').each(function (i) {
                    $(this).quicksearch("[id*=GridView1] tr:not(:has(th))", {
                        'testQuery': function (query, txt, row) {
                            return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
                        }
                    });
                });
            });
                </script>
            </div>
        </form>
    </body>
    </html>
    

    Code-behind:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace AspNetNormalIssue.Webform
    {
        public partial class GridviewWithQuickSearch : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGrid();
                }
    
            }
            private void BindGrid()
            {
                DataTable d1 = new DataTable();
                d1.Columns.Add("id");
                d1.Columns.Add("Subject");
                d1.Columns.Add("SelectSource");
                d1.Columns.Add("SourceName");
                d1.Rows.Add("1","aa","bbbb","aaaaaaa");
                d1.Rows.Add("2", "bb", "ccccc", "dddddd");
                d1.Rows.Add("3", "cccc", "dddd", "fffff");
                d1.Rows.Add("4", "dddd", "eeee", "ffff");
                d1.Rows.Add("5", "eee", "cccc", "asdasdas");
                d1.Rows.Add("6", "fff", "werwer", "qweqwe");
                GridView1.DataSource = d1;
                GridView1.DataBind();
                //string constr = ConfigurationManager.ConnectionStrings["AIO"].ConnectionString;
                //using (SqlConnection con = new SqlConnection(constr))
                //{
                //    using (SqlCommand cmdinternal = new SqlCommand())
                //    {
                //        cmdinternal.CommandText = "SELECT id, SourceName, SelectSource , Subject from tbl_requestPrintGOV ";
                //        cmdinternal.Connection = con;
                //        con.Open();
                //        GridView1.DataSource = cmdinternal.ExecuteReader();
                //        GridView1.DataBind();
                //        con.Close();
                //    }
                //}
            }
    
            protected void OnDataBound(object sender, EventArgs e)
            {
                GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
                for (int i = 0; i < GridView1.Columns.Count; i++)
                {
                    TableHeaderCell cell = new TableHeaderCell();
                    TextBox txtSearch = new TextBox();
                    txtSearch.Attributes["placeholder"] = GridView1.Columns[i].HeaderText;
                    txtSearch.CssClass = "search_textbox";
                    cell.Controls.Add(txtSearch);
                    row.Controls.Add(cell);
                }
                GridView1.HeaderRow.Parent.Controls.AddAt(1, row);
            }
    
            protected void DownloadFile(object sender, EventArgs e)
            {
       
                int id = int.Parse((sender as LinkButton).CommandArgument) + 1;
                int i = 0;
                //byte[] bytes;
                //string fileName, contentType;
                //string constr = ConfigurationManager.ConnectionStrings["AIO"].ConnectionString;
                //using (SqlConnection con = new SqlConnection(constr))
                //{
                //    using (SqlCommand cmdinternal = new SqlCommand())
                //    {
                //        cmdinternal.CommandText = "select Name, Data, ContentType from tbl_requestPrintGOV where Id=@Id ";
                //        cmdinternal.Parameters.AddWithValue("@Id", id);
                //        cmdinternal.Connection = con;
                //        con.Open();
                //        using (SqlDataReader sdr = cmdinternal.ExecuteReader())
                //        {
                //            sdr.Read();
                //            bytes = (byte[])sdr["Data"];
                //            contentType = sdr["ContentType"].ToString();
                //            fileName = sdr["Name"].ToString();
                //        }
                //        con.Close();
                //    }
                //}
                //Response.Clear();
                //Response.Buffer = true;
                //Response.Charset = "";
                //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                //Response.ContentType = contentType;
                //Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
                //Response.BinaryWrite(bytes);
                //Response.Flush();
                //Response.End();
            }
        }
    }

    Result:

    Best Regards,

    Brando

    Thursday, July 5, 2018 6:33 AM
  • User-1171043462 posted

    Please try now

    HTML

    <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
            runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound">
            <Columns>
                <asp:BoundField DataField="id" HeaderText="Id" ItemStyle-Width="30" />
                <asp:BoundField DataField="Subject" HeaderText="Subject" ItemStyle-Width="100" />
                <asp:BoundField DataField="SelectSource" HeaderText="SelectSource" ItemStyle-Width="100" />
                <asp:BoundField DataField="SourceName" HeaderText="Source Name" ItemStyle-Width="100" />
    
                <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Operation">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkDownload"   runat="server" Text=" Download" OnClick="DownloadFile"
                                CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
                        </ItemTemplate>
    		  <ItemStyle HorizontalAlign="Center"></ItemStyle>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:HiddenField Id = "hfId" runat = "server" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript" src="quicksearch.js"></script>
        <script type="text/javascript">
            $(function () {
    	    $("[id*=lnkDownload=]").click(function(){
    		var id = $(this).closest("tr").find("td").eq(0).html();
    		$("[id*=hfId]").val(id);
    	    });
                $('.search_textbox').each(function (i) {
                    $(this).quicksearch("[id*=GridView1] tr:not(:has(th))", {
                        'testQuery': function (query, txt, row) {
                            return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
                        }
                    });
                });
            });
        </script>

    Code

    protected void DownloadFile(object sender, EventArgs e)
        {
            
            //int id = int.Parse((sender as LinkButton).CommandArgument);
    	int id = int.Parse(Request.Form[hfId.UniqueID]);
            byte[] bytes;
            string fileName, contentType;
            string constr = ConfigurationManager.ConnectionStrings["AIO"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmdinternal = new SqlCommand())
                {
                    cmdinternal.CommandText = "select Name, Data, ContentType from tbl_requestPrintGOV where Id=@Id ";
                    cmdinternal.Parameters.AddWithValue("@Id", id);
                    cmdinternal.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmdinternal.ExecuteReader())
                    {
                        sdr.Read();
                        bytes = (byte[])sdr["Data"];
                        contentType = sdr["ContentType"].ToString();
                        fileName = sdr["Name"].ToString();
                    }
                    con.Close();
                }
            }
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = contentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }

    Thursday, July 5, 2018 10:40 AM