How can I click on gridview row and display the record of the row that was clicked on another page?

Donald Symmons 2,861 Reputation points
2022-07-05T16:23:28.047+00:00

Hello,
Please I am trying to create a situation where I click on a row in gridview and redirect to another page to display the record or data of that particular row I clicked on another page. for example, I have a gridview in page1 and when I click on a row in that gridview, I redirect to page2 to display the record of that gridview row of page1 in page2. Here is what I tried but when I redirected to page2, but it did not show anything. it just showed a blank page.
What I want to show is a a pdf file, so I made use of Generic handler

Please I need your help

Here is my HTML and code

Page1

  <asp:GridView ID="GridView2" runat="server" GridLines="None" DataKeyNames="Name" AllowPaging="true" HeaderStyle-ForeColor="#05214d" HeaderStyle-Font-Bold="false" HeaderStyle-Font-Size="11pt" Font-Size="10pt"  
                                        AutoGenerateColumns="false" OnSelectedIndexChanged="OnSelectedIndexChanged" OnRowDataBound="OnRowDataBound" HeaderStyle-HorizontalAlign="left" RowStyle-HorizontalAlign="Left" OnPageIndexChanging="OnPageIndexChanging" class="table" Width="100%">  
                                        <EmptyDataTemplate>  
                                            <div style="text-align: center; font-weight: bolder;">  
                                                <hr />  
                                                <hr />  
                                                <asp:Label ID="labelTemp" runat="server" Font-Names="Roboto" Font-Size="12pt" Text="No Record Available"></asp:Label>  
                                                <hr />  
                                                <hr />  
                                            </div>  
                                        </EmptyDataTemplate>  
                                        <Columns>  
                                            <asp:BoundField DataField="Name" HeaderText="File Name" />  
                                            <asp:BoundField DataField="CreatedBy" HeaderText="Created By" />  
                                            <asp:BoundField DataField="CreatedDate" HeaderText="Date Created" />  
                                        </Columns>  
                                    </asp:GridView>  

Page1.aspx.cs (C#)

  protected void OnRowDataBound(object sender, GridViewRowEventArgs e)  
    {  
        if (e.Row.RowType == DataControlRowType.DataRow)  
        {  
            e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView2, "Select$" + e.Row.RowIndex);  
            e.Row.Style.Add("cursor", "pointer");  
            e.Row.ToolTip = "Click to view this document.";  
        }  
    }  
  
    protected void OnSelectedIndexChanged(object sender, EventArgs e)  
    {  
        foreach (GridViewRow row in GridView2.Rows)  
        {  
            if (row.RowIndex == GridView2.SelectedIndex)  
            {  
                int index = GridView2.SelectedIndex;  
                Session["RowIndex"] = GridView2.DataKeys[index].Value.ToString();  
                Response.Redirect("details.aspx?RowIndex=" + row.RowIndex);  
            }  
        }  
    }  

Page2

  <div class="contentt">  
                                <asp:Literal ID="ltEmbed" runat="server" />  
                            </div>  

Page2.aspx.cs

   protected void Page_Load(object sender, EventArgs e)  
    {  
        if (Session["user"] == null)  
        {  
            Response.Redirect("login.aspx");  
        }  
        else  
        {  
            if (this.Page.PreviousPage != null)  
            {  
                int rowIndex = int.Parse(Request.QueryString["RowIndex"]);  
                GridView Gridview2 = (GridView)this.Page.PreviousPage.FindControl("Gridview2");  
                GridViewRow row = Gridview2.Rows[rowIndex];  
                BindDocument();  
            }  
        }  
    }  
  
    private void BindDocument()  
    {  
        if (Session["RowIndex"] != null)  
        {  
            int id = Convert.ToInt32(Request.QueryString["Id"]);  
  
            string sql = "SELECT * FROM tableinvoice WHERE Id = @Id";  
            SqlParameter[] parameters = new[] { new SqlParameter("@Id", id) };  
  
            // Bind Image3 for Card Image  
            DataTable dt = SelectFromDatabase(sql, parameters);  
  
            string embed = "<object data=\"{0}{1}\" type=\"application/pdf\"></object>";  
            ltEmbed.Text = string.Format(embed, ResolveUrl("pdfdetail.ashx?Id="), id);  
        }  
    }  
  
  public static DataTable SelectFromDatabase(string sql, SqlParameter[] parameters)  
    {  
        using (SqlConnection con = new SqlConnection("Data Source=N1NWPLSK12SQL-v02.shr.prod.ams1.secureserver.net;Initial Catalog=Quirver_DB;Persist Security Info=True;User ID=quirverT;Password=**************"))  
        {  
  
            using (SqlCommand cmd = new SqlCommand(sql, con))  
            {  
                if (parameters != null)  
                {  
                    cmd.Parameters.AddRange(parameters);  
                }  
  
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))  
                {  
                    DataTable dt = new DataTable();  
                    sda.Fill(dt);  
                    return dt;  
                }  
            }  
        }  
    }  

Generic Handler

    public void ProcessRequest (HttpContext context)  
    {  
        //int id = Convert.ToInt32(Request.QueryString["Id"]);  
        int id = int.Parse(context.Request.QueryString["Id"]);  
        byte[] bytes;  
        string contentType;  
        string constr = "Data Source=N1NWPLSK12SQL-v02.shr.prod.ams1.secureserver.net;Initial Catalog=Quirver_DB;Persist Security Info=True;User ID=quirverT;Password=***************";  
        using (SqlConnection con = new SqlConnection(constr))  
        {  
            using (SqlCommand cmd = new SqlCommand())  
            {  
                cmd.CommandText = "SELECT * FROM tableinvoice WHERE Id=@Id";  
                cmd.Parameters.AddWithValue("@Id", id);  
                cmd.Connection = con;  
                con.Open();  
                using (SqlDataReader sdr = cmd.ExecuteReader())  
                {  
                    sdr.Read();  
                    bytes = (byte[])sdr["Data"];  
                    contentType = sdr["ContentType"].ToString();  
                }  
                con.Close();  
            }  
        }  
  
        context.Response.Buffer = true;  
        context.Response.Charset = "";  
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);  
        context.Response.ContentType = contentType;  
        context.Response.BinaryWrite(bytes);  
        context.Response.Flush();  
        context.Response.End();  
    }  
  
    public bool IsReusable {  
        get {  
            return false;  
        }  
    }  
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,417 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Albert Kallal 5,231 Reputation points
    2022-07-06T21:15:41.063+00:00

    Ok it looks like there is two questions and parts here.

    First part - row click in a grid - jump to next page, and display details of that one row click.

    You as a general rule can't use Page.Previous UNLESS you use a button (hyper hlink) with a post-back URL. However, we don't really need that anyway.

    So, lets address the part one of your question.

    Here is a simple grid view - we also dropped in a button into that row for the row click.

    so, we have this:

    218362-image.png

    so, some columns, and we just dropped in a plane jane button. Note the click event we added to the button.

    Ok, so now our code to fill, say this:

       protected void Page_Load(object sender, EventArgs e)  
        {  
            if (!IsPostBack)  
                LoadData();  
        }  
    
        void LoadData()  
        {  
            string strSQL = "SELECT * FROM tblHotelsA ORDER BY HoteName";  
            DataTable rstData = General.MyRst(strSQL);  
            GridView1.DataSource = rstData;  
            GridView1.DataBind();  
        }  
    
      
    

    And now we have/see this:

    218391-image.png

    So, all we need now is the code for clicking on the one row button, and then we jump to the next page.

    So,

    The button click code can be this:

            protected void cmdEdit_Click(object sender, EventArgs e)  
            {  
                Button btn = sender as Button;  
                GridViewRow gRow = btn.NamingContainer as GridViewRow;  
                int? PKID = (int?)GridView1.DataKeys[gRow.RowIndex]["ID"];  
      
                Session["PKID"] = PKID;  
                Response.Redirect("HotelEditOne.aspx");  
            }  
      
    

    Note the use of data keys. It is a nice feature, since we do not have to show/display/hide the database PK row id, but we are as above shows free to get and grab that database row PK id.

    So, now we navigate to the next page.

    The markup can be just plane text, does not matter a whole lot, but the code to load on that 2nd page can be this:

            protected void Page_Load(object sender, EventArgs e)  
            {  
                if (!IsPostBack)  
                    LoadData();  
            }  
      
      
            void LoadData ()  
            {  
                int PKID = (int)Session["PKID"];  
                string strSQL = "SELECT * FROM tblHotelsA WHERE ID = " + PKID;  
                DataRow rstData = General.MyRst(strSQL).Rows[0];  
      
                txtHotel.Text = rstData["HotelName"].ToString();  
                tFN.Text = rstData["FirstName"].ToString();  
                tLN.Text = rstData["LastName"].ToString();  
                tCity.Text = rstData["City"].ToString();  
                tProvince.Text = rstData["Province"].ToString();  
                chkActive.Checked = (bool)rstData["Active"];  
                chkBalcony.Checked = (bool)rstData["Balcony"];  
                txtNotes.Text = rstData["Description"].ToString();  
      
            }  
      
    

    And now we get / see this:

    218257-image.png

    so, that is really quite much the whole layout and approach to a row click from a grid.

    the next issue of course is that you not really looking to display data on that 2nd page, but in fact display a PDF file - a VAST different goal and request.

    but, the above does show how to get he database PK row id, shows how to jump to the next page, and pass that PK value.

    So, if I have time, then perhaps we deal with the 2nd part of your question - the display of PDF, which, as noted, is not really data base operations anymore.

    So, study above - see how we pick up the PK row from the database.

    I also of course used a global helper routine - that just returns a datatable for a given query - and I sure after one day of typing that kind of code over and over, you also built your own such routine (to save the keyboard!!!). That code was this:

            public static DataTable MyRst(string strSQL)  
            {  
                DataTable rstData = new DataTable();  
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))  
                {  
                    using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))  
                    {  
                        cmdSQL.Connection.Open();  
                        rstData.Load(cmdSQL.ExecuteReader());  
                    }  
                }  
                return rstData;  
            }  
      
    

    Regards,
    Albert D. Kallal (Access MVP 2003-2017)
    Edmonton, Alberta Canada


  2. Albert Kallal 5,231 Reputation points
    2022-07-07T15:48:46.98+00:00

    Well, you don't have to make it global, but it just that I became oh so tired of typing what amounts to the same code over and over in the applcation.

    So, when building a applcation, I have have 20 or even 30 helper routines. These are routines that I lift/grab/take from previous projects. So, you can create a new global class, and in that static class, just drop in your many helper routines (say date conversions, routines to execute sql statements etc.).

    in vb.net, you just create a plane jane module (add module to your project). In c#, you create a static class, and it might look like say this:

        public static class General  
        {  
      
            public static DataTable MyRst(string strSQL)  
            {  
                DataTable rstData = new DataTable();  
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))  
                {  
                    using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))  
                    {  
                        cmdSQL.Connection.Open();  
                        rstData.Load(cmdSQL.ExecuteReader());  
                    }  
                }  
                return rstData;  
            }  
      
      
            public static DataTable MyRstP(SqlCommand cmdSQL)  
            {  
                DataTable rstData = new DataTable();  
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))  
                {  
                    using (cmdSQL)  
                    {  
                        cmdSQL.Connection = conn;  
                        conn.Open();  
                        rstData.Load(cmdSQL.ExecuteReader());  
                    }  
                }  
                return rstData;  
            }  
    

    I mean, you are free to just drop that code into the existing web page, say like this:

           public DataTable MyRst(string strSQL)  
            {  
                DataTable rstData = new DataTable();  
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))  
                {  
                    using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))  
                    {  
                        cmdSQL.Connection.Open();  
                        rstData.Load(cmdSQL.ExecuteReader());  
                    }  
                }  
                return rstData;  
    

    so, no real need to make it global to your project - but, it just makes sense to have a few handy dandy routines - no reason to type such little bits of code over and over.

    0 comments No comments