Redirect to another page with selected GridView Row on Click using C# in ASP.Net

RichardSa
 
on Aug 27, 2021 08:54 PM
Sample_675752.zip
681 Views

I searched and found how to pass Grid-view row data to another page. But when I click on my Gridview nothing happens. It is not redirecting to the next page.

My Gridview has OnPageIndexChanging where I click to change Gridview pages. Also, I use stored procedure for the Gridview. I really don’t know why it is not working when I click on a row

Here is my code and gridview

<asp:UpdatePanel runat="server" ID="paneltemp">
    <ContentTemplate>
        <asp:GridView ID="GridView1" runat="server" GridLines="None" AllowPaging="true" HeaderStyle-ForeColor="#eeeeee" HeaderStyle-Font-Bold="true" HeaderStyle-BackColor="#224f6d"
            AutoGenerateColumns="false" OnSelectedIndexChanged="OnSelectedIndexChanged" OnPageIndexChanging="OnPageIndexChanging" OnRowDataBound="OnRowDataBound" class="table" Width="100%" HeaderStyle-HorizontalAlign="left" RowStyle-HorizontalAlign="Left">
            <Columns>
                <asp:BoundField DataField="Election_Name" HeaderText="ELECTION NAME" />
                <asp:BoundField DataField="Start_Date" HeaderText="START DATE" ReadOnly="true" />
                <asp:BoundField DataField="End_Date" HeaderText="END DATE" />
            </Columns>
        </asp:GridView>
        <hr />
        <div style="float: left; font-size: 10pt; margin-right: 1%; font-weight: 600;">
            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" />
            Election(s))&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 />
    </ContentTemplate>
</asp:UpdatePanel>

 

 private int PageSize = 4;
 
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!this.IsPostBack)
     {
         this.ElectionPage(1);
     }
 }
 
 private void ElectionPage(int pageIndex)
 {
     using (SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\BallotDB.mdf;Integrated Security = True;"))
     {
         using (SqlCommand cmd = new SqlCommand("ElectionData", con))
         {
             cmd.CommandType = CommandType.StoredProcedure;
             cmd.Parameters.AddWithValue("@Name", userlabel.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);
                     con.Close();
                     int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
                     this.PopulatePager(recordCount, 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 Page_Changed(object sender, EventArgs e)
 {
     int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
     this.ElectionPage(pageIndex);
 }
 
 protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
 {
     GridView1.PageIndex = e.NewPageIndex;
     this.ElectionPage(1);
 }
 protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         e.Row.Cells[2].Text = Convert.ToDateTime(e.Row.Cells[2].Text.Replace("T", " ")).ToString("d, MMM yyyy hh:mm tt");
         e.Row.Cells[1].Text = Convert.ToDateTime(e.Row.Cells[1].Text.Replace("T", " ")).ToString("d, MMM yyyy hh:mm tt");
         e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
         e.Row.Style.Add("cursor", "pointer");
        // e.Row.Attributes["style"] = "cursor:pointer";
         e.Row.ToolTip = "Click to select this row.";
     }
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
     foreach (GridViewRow row in GridView1.Rows)
     {
         if (row.RowIndex == GridView1.SelectedIndex)
         {
             Response.Redirect("summary.aspx?Name=" + row.Cells[0].Text.Trim());
         }
     }
 }

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 28, 2021 02:08 AM
on Aug 28, 2021 02:25 AM

Hi RichardSam,

Since you are attaching the event directly to the GridView Row which by default does not have any OnClick event, you need to set the property EnableEventValidation = "false" in the @Page Directive.

For more details refer below article.

Select GridView Row on Row Click in ASP.Net

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Procedure

CREATE PROCEDURE [dbo].[Customers_GetCustomersPageWise]  
	@PageIndex INT = 1,
	@PageSize INT = 20,
	@RecordCount INT OUTPUT
AS
BEGIN	
	SET NOCOUNT ON;

	SELECT  (ROW_NUMBER() OVER(Order By CustomerId)) AS RowNumber,
			[CustomerID]
			,[CompanyName]
			,[ContactName]
			,[ContactTitle]
			,[Address]
			,[City]
			,[Region]
			,[PostalCode]
			,[Country]
			,[Phone]
			,[Fax]
	INTO #Results	
	FROM [Customers]	

	SELECT @RecordCount = Count(*) FROM #Results

	SELECT * FROM #Results WHERE 
	ROWNUMBER BETWEEN  (@PageIndex-1)*@PageSize + 1 AND (((@PageIndex-1)*@PageSize + 1)+@PageSize)-1 OR @PageIndex = -1

	DROP TABLE #Results
END

HTML

<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server" ID="paneltemp">
    <ContentTemplate>
        <asp:GridView ID="GridView1" runat="server" GridLines="None" AllowPaging="true" HeaderStyle-ForeColor="#eeeeee" HeaderStyle-Font-Bold="true" HeaderStyle-BackColor="#224f6d"
            AutoGenerateColumns="false" OnSelectedIndexChanged="OnSelectedIndexChanged" OnPageIndexChanging="OnPageIndexChanging" OnRowDataBound="OnRowDataBound" class="table" Width="100%" 
            HeaderStyle-HorizontalAlign="left" RowStyle-HorizontalAlign="Left">
            <Columns>
                <asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
                <asp:BoundField DataField="City" HeaderText="City" ReadOnly="true" />
                <asp:BoundField DataField="Country" HeaderText="Country" />
            </Columns>
        </asp:GridView>
        <hr />
        <div style="float: left; font-size: 10pt; margin-right: 1%; font-weight: 600;">
            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" />
            Election(s))&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 />
    </ContentTemplate>
</asp:UpdatePanel>

Namespaces

using System.Data;
using System.Data.SqlClient;

Code

private int PageSize = 4;
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.ElectionPage(1);
    }
}

private void ElectionPage(int pageIndex)
{
    using (SqlConnection con = new SqlConnection("Data Source = .;DataBase=Northwind;UID=sa;PWD=pass@123;"))
    {
        using (SqlCommand cmd = new SqlCommand("Customers_GetCustomersPageWise", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            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);
                    con.Close();
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                    int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
                    this.PopulatePager(recordCount, 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 Page_Changed(object sender, EventArgs e)
{
    int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
    this.ElectionPage(pageIndex);
}

protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    this.ElectionPage(1);
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //e.Row.Cells[2].Text = Convert.ToDateTime(e.Row.Cells[2].Text.Replace("T", " ")).ToString("d, MMM yyyy hh:mm tt");
        //e.Row.Cells[1].Text = Convert.ToDateTime(e.Row.Cells[1].Text.Replace("T", " ")).ToString("d, MMM yyyy hh:mm tt");
        e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
        e.Row.Style.Add("cursor", "pointer");
        e.Row.ToolTip = "Click to select this row.";
    }
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        if (row.RowIndex == GridView1.SelectedIndex)
        {
            Response.Redirect("summary.aspx?Name=" + HttpUtility.UrlEncode(row.Cells[0].Text.Trim()));
        }
    }
}

Screenshot