my GridView does not show, on page except I click on a button on the page

Donald Symmons 3,066 Reputation points
2024-01-04T04:55:43.36+00:00

I have two GridViews and two pages(Page1 and Page2), one GridView on each page. When I click on a row in the Page1 Gridview, it redirects me to Page2 GridView and display detail records in that Page2 GridView. But in my case, when it redirects to Page2 the GridView does not show. Instead I get the "EmptyDataTemplate" of the GridView, which indicates that there are no records in the GridView. However, when I click on the search button on top of that Page2 GridView, the GridView on Page2 shows with the records displayed.

I am not using the Table Id as my index, because I need to display multiple records belonging to the same parameter. For example, the Page1 GridView contains an event data like event Id, event name, event time and date, venue etc... while Page2 Gridview has data of people registered for the event. The parameter that I used to connect the two GridViews is event Id (which is not an INTEGER).

Page1 GridView

<asp:UpdatePanel ID="panel" runat="server" ChildrenAsTriggers="true">
                            <ContentTemplate>
                                <div class="container-fluid p-3 mb5 bg-white rounded" id="card" style="margin: 0 auto; padding: 10px; border: 1.3px solid #e4e7e8;">
                                    <div style="width: 100%; margin: 0 auto; padding: 5px; border-radius: 5px; border: 0.3px solid #c7c7c7; float: right; text-align: center; margin-top: 0%;">
                                        <asp:Button ID="NewDocument" runat="server" Font-Size="10px" Text="New Event" CssClass="btn btn-primary" OnClick="NewDocument_Click" />
                                    </div>
                                    <div class="grid-corner" style="width: 100%; background-color: white; font-size: 8pt; margin: 0 auto; padding: 5px;">
                                        <asp:GridView ID="GridView1" runat="server" GridLines="None" DataKeyNames="eventId" HeaderStyle-BackColor="#fdfdfd" AllowPaging="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="#05214d" HeaderStyle-Font-Size="11pt" Font-Size="9pt"
                                            AutoGenerateColumns="false"  OnSelectedIndexChanged="OnSelectedIndexChanged" HeaderStyle-HorizontalAlign="left" RowStyle-HorizontalAlign="Left" OnPageIndexChanging="OnPageIndexChanging" class="table" Width="100%">
                                            <EmptyDataTemplate>
                                                <div style="text-align: center; font-weight: 500; margin-top: 2%;">
                                                    <i class="fal fa-file-times" style="margin: 0 auto; font-size: 30pt; color: #145c7c;"></i>
                                                    <p id="P1" runat="server" style="font-size: 11pt; font-weight: 400;">You have not created any event yet</p>
                                                </div>
                                            </EmptyDataTemplate>
                                            <Columns>
                                                <asp:TemplateField>
                                                    <ItemTemplate>
                                                        <asp:LinkButton ID="Linkdelete" OnClientClick="return confirm('Are you sure to delete this entry?');" runat="server" OnClick="Linkdelete_Click">
                                                            <i class="fal fa-trash" aria-hidden="true" style="margin: 0 7px; font-size: 10pt; color: #145c7c;"></i>
                                                        </asp:LinkButton>
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                                <asp:BoundField DataField="Id" HeaderText="ID" HeaderStyle-Font-Bold="false" />
                                                <asp:BoundField DataField="eventName" HeaderText="Type" HeaderStyle-Font-Bold="false" />
                                                <asp:BoundField DataField="eventId" HeaderText="Event ID" HeaderStyle-Font-Bold="false" />
                                                <asp:BoundField DataField="eventTopic" HeaderText="Event" HeaderStyle-Font-Bold="false" />
                                                <asp:BoundField DataField="StartDate" HeaderText="From" HeaderStyle-Font-Bold="false" />
                                                <asp:BoundField DataField="EndDate" HeaderText="To" HeaderStyle-Font-Bold="false" />
                                                <asp:BoundField DataField="Person" HeaderText="Created By" HeaderStyle-Font-Bold="false" />
                                                <asp:BoundField DataField="CreatedDate" HeaderText="Created Date" HeaderStyle-Font-Bold="false" />
                                                <asp:TemplateField HeaderText="Status" HeaderStyle-Font-Bold="false">
                                                    <ItemTemplate>
                                                        <asp:UpdatePanel runat="server">
                                                            <ContentTemplate>
                                                                <div class="badge badge-pill badge-success" runat="server" id="notstart" style="font-weight: 400; font-size: 9pt;">Processing</div>
                                                                <div class="badge badge-pill badge-info" runat="server" id="running" style="font-weight: 400; font-size: 9pt;">Ongoing</div>
                                                                <div class="badge badge-pill badge-warning" runat="server" id="ended" style="font-weight: 400; font-size: 9pt;">Ended</div>
                                                            </ContentTemplate>
                                                        </asp:UpdatePanel>
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                            </Columns>
                                        </asp:GridView>
                                        <div style="float: right; font-size: 10pt; margin-right: 1%;">
                                            Showing&nbsp;Page&nbsp;
        <asp:Label ID="lblPageIndex" runat="server" Text="Label" />
                                            &nbsp;of&nbsp;
        <asp:Label ID="lblTotalPage" runat="server" />
                                            (<asp:Label ID="lblTotal" runat="server" />
                                            Records)&nbsp;&nbsp;
        <div class="dvPager">
            <asp:Repeater ID="rptPager" runat="server">
                <ItemTemplate>
                    <asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
                        CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
                        OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
                </ItemTemplate>
            </asp:Repeater>
        </div>
                                        </div>
                                        <br />
                                        <br />
                                    </div>
                                </div>
                            </ContentTemplate>
                        </asp:UpdatePanel>

Page1 C#

protected void Page_Load(object sender, EventArgs e)
        {
                if (!this.IsPostBack)
                {
                    GetDataGridview();
                }
        }
 public void GetDataGridview()
        {
            string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM EventTable"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {

                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);

                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
                    }
                }
            }
            this.GetEventRecord(1);
        }
        int PageSize = 10;
        private void GetEventRecord(int pageIndex)
        {
            try
            {
                using (SqlConnection con = new SqlConnection())
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                    using (SqlCommand cmd = new SqlCommand("EventList", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@CreatedBy", createby.Text.Trim());
                        cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
                        cmd.Parameters.AddWithValue("@PageSize", PageSize);
                        cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
                        cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
                        con.Open();
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);
                                upload.Visible = true;
                                GridView1.DataSource = dt;
                                GridView1.DataBind();
                                int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
                                this.PopulatePager(recordCount, pageIndex);
                            }
                        }
                        con.Close();
                    }
                }
            }
            catch (SqlException ex)
            {
                string msg = "Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
        }
        protected void Page_Changed(object sender, EventArgs e)
        {
            int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
            this.GetEventRecord(pageIndex);
        }
        private void PopulatePager(int recordCount, int currentPage)
        {
            double dblPageCount = (double)((decimal)recordCount / (decimal)PageSize);
            int pageCount = (int)Math.Ceiling(dblPageCount);
            List<ListItem> pages = new List<ListItem>();
            if (pageCount > 0)
            {
                if (currentPage != 1)
                {
                    pages.Add(new ListItem("Prev", (currentPage - 1).ToString()));
                }
                if (pageCount < 4)
                {
                    for (int i = 1; i <= pageCount; i++)
                    {
                        pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                }
                else if (currentPage < 4)
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                    pages.Add(new ListItem("...", (currentPage).ToString(), false));
                }
                else if (currentPage > pageCount - 4)
                {
                    pages.Add(new ListItem("...", (currentPage).ToString(), false));
                    for (int i = currentPage - 1; i <= pageCount; i++)
                    {
                        pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                }
                else
                {
                    pages.Add(new ListItem("...", (currentPage).ToString(), false));
                    for (int i = currentPage - 2; i <= currentPage + 2; i++)
                    {
                        pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                    pages.Add(new ListItem("...", (currentPage).ToString(), false));
                }
                if (currentPage != pageCount)
                {
                    pages.Add(new ListItem("Next", (currentPage + 1).ToString()));
                }
            }
            rptPager.DataSource = pages;
            rptPager.DataBind();

            lblPageIndex.Text = currentPage.ToString();
            lblTotalPage.Text = ((recordCount / PageSize) + ((recordCount % PageSize) > 0 ? 1 : 0)).ToString();
            lblTotal.Text = recordCount.ToString();
        }
        protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.GetEventRecord(1);
        }
protected void OnSelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowIndex == GridView1.SelectedIndex)
                {
                   Response.Redirect("/accesslog?eventId=" + HttpUtility.UrlEncode(row.Cells[3].Text.Trim()));
                }
            }
        }

Page2 GridView

<div style="width: 100%; margin: 0 auto; padding: 10px; border-radius: 5px; border: 0.3px solid #c7c7c7; margin-top: 0%;">
                            <div class="input-group" style="width: 40%; padding: 5px; float: right;">
                                <asp:TextBox ID="Searchbox" runat="server" placeholder="File Name" CssClass="form-control" Font-Size="10pt"></asp:TextBox>
                                <div class="input-group-append">
                                    <button id="searchbtn" runat="server" class="btn btn-primary" backcolor="SteelBlue" style="height: auto; background-color: transparent; border: 0.3px solid #d6d8d9; color: #404344;">
                                        <i class="far fa-search" aria-hidden="true" style="font-size: 11pt;"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="container-fluid p-3 mb5 bg-white rounded" style="margin: 0 auto; padding: 10px; border: 1.3px solid #e4e7e8;">
                            <div class="grid-corner" style="width: 100%; background-color: white; font-size: 9pt; margin: 0 auto; padding: 5px;">
                                <asp:GridView ID="GridView1" runat="server" GridLines="None" HorizontalAlign="Center" RowStyle-Width="100%" RowStyle-CssClass="table" CssClass="table" DataKeyNames="eventId" CellPadding="8" CellSpacing="5" AllowPaging="true" PageSize="15" HeaderStyle-ForeColor="#05214d" HeaderStyle-Font-Size="10pt" Font-Size="10pt"
                                    AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" HeaderStyle-HorizontalAlign="left" RowStyle-HorizontalAlign="Left" OnPageIndexChanging="OnPageIndexChanging" HeaderStyle-BackColor="#f5f5f5" RowStyle-BackColor="#fdfdfd" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000" Width="100%">
                                    <EmptyDataTemplate>
                                        <div class="alert alert-success" style="text-align: center; font-weight: 500; margin-top: 2%;">
                                            <i class="fal fa-file-times" style="margin: 0 auto; font-size: 20pt; color: #145c7c;"></i>
                                            <p id="P2" runat="server" style="font-size: 11pt; font-weight: 400;">No registration has been done for this event yet</p>
                                        </div>
                                    </EmptyDataTemplate>
                                    <Columns>
                                        <asp:TemplateField>
                                            <ItemTemplate>
                                                <asp:LinkButton ID="Linkdelete" OnClientClick="return confirm('Are you sure to delete this record?');" runat="server" OnClick="Linkdelete_Click">
                                                       <i class="fad fa-trash" aria-hidden="true" style="margin: 0 7px; font-size: 10pt; color: #145c7c;"></i>
                                                </asp:LinkButton>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:BoundField DataField="Id" HeaderText="ID" HeaderStyle-Font-Bold="false" />
                                        <asp:BoundField DataField="eventId" HeaderText="Event ID" HeaderStyle-Font-Bold="false" />
                                        <asp:BoundField DataField="accessid" HeaderText="ID" HeaderStyle-Font-Bold="false" ItemStyle-Font-Size="10pt" />
                                        <asp:BoundField DataField="RegName" HeaderText="Name" HeaderStyle-Font-Bold="false" ItemStyle-Font-Size="10pt" />
                                        <asp:BoundField DataField="inviteeMail" HeaderText="Email" HeaderStyle-Font-Bold="false" ItemStyle-Font-Size="10pt" />
                                        <asp:BoundField DataField="RegDate" HeaderText="Date Registered" HeaderStyle-Font-Bold="false" ItemStyle-Font-Size="10pt" />
                                    </Columns>
                                </asp:GridView>
                                <br />
                            </div>
                        </div>

Page2 C#

protected void Page_Load(object sender, EventArgs e)
        {
            BindGrid();
            pLabel.Text = HttpUtility.UrlDecode(Request.QueryString["eventId"]);
        }
private void BindGrid()
        {
            try
            {
                using (SqlConnection con = new SqlConnection())
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                    using (SqlCommand cmd = new SqlCommand("SELECT Id, eventId, accessid, RegName, inviteeMail, RegDate FROM EventRegister WHERE eventId=@eventId AND CreatedBy=@CreatedBy ORDER BY Id DESC"))
                    {
                        cmd.Parameters.AddWithValue("@eventId", pLabel.Text.Trim());
                        cmd.Parameters.AddWithValue("@CreatedBy", createby.Text.Trim());
                        con.Open();
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);
                                using (SqlDataReader dr = cmd.ExecuteReader())
                                    if (dr.HasRows)
                                    {
                                        GridView1.DataSource = dt;
                                        GridView1.DataBind();
                                        Printbtn.Enabled = true;
                                    }
                                    else
                                    {
                                        Printbtn.Enabled = false;
                                        GridView1.DataSource = dt;
                                        GridView1.DataBind();
                                    }
                            }
                        }
                        con.Close();
                    }
                }
            }
            catch (SqlException ex)
            {
                string msg = "Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
        }
        protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }
protected void Linkdelete_Click(object sender, EventArgs e)
        {
            try
            {
                int rowindex = ((GridViewRow)(sender as System.Web.UI.Control).NamingContainer).RowIndex;
                string Id = GridView1.Rows[rowindex].Cells[1].Text;
                using (SqlConnection con = new SqlConnection())
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                    using (SqlCommand cmd = new SqlCommand("DELETE FROM EventRegister WHERE Id = @Id", con))
                    {
                        cmd.Parameters.AddWithValue("@Id", Id);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        this.BindGrid();
                    }
                }
            }
            catch (SqlException ex)
            {
                string msg = "Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
        }
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,103 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,598 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,181 Reputation points Microsoft External Staff
    2024-01-04T05:57:17.2233333+00:00

    Hi @Donald Symmons,

    You need to assign the Label first, then bind the data and make sure you pass the correct value.

    Page2 C#

     protected void Page_Load(object sender, EventArgs e)
            {
                if (!this.IsPostBack)
                {                
                    pLabel.Text = HttpUtility.UrlDecode(Request.QueryString["eventId"]);
                    BindGrid();
                }
            }
    

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.