3

I have a following GridView defined in my user control page named GridControl.ascx.

<asp:GridView ID="GridProd" runat="server" RowStyle-CssClass="GridProdGrid" 
    BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
    BorderWidth="1px" CellPadding="10" ForeColor="Black" GridLines="Vertical" 
    AutoGenerateEditButton="True" OnRowEditing="GridProd_RowEditing" 
    AllowSorting="True" OnSorting="Set_Sort" DataKeyNames="ProductID" 
    AutoGenerateColumns="False" AutoGenerateSelectButton="True" 
    OnSelectedIndexChanging="GridProd_SelectedIndexChanging">

I am using this control on ProductList.aspx. Basically I want to display only the selected items on my another page named ItemList.aspx. I am trying to use the following code but it is throwing me null reference exception.

GridView gd = (GridView)this.Page.PreviousPage.FindControl("GridProd");

/*For each row in GridView gd obtained from previous page*/
foreach (GridViewRow rows in gd.Rows)
{
    /*We will get the checkbox to check if it's checked or not*/
    CheckBox cb = (CheckBox)rows.FindControl("checktoadd");

    if (cb.Checked)
    {
        string prodname = rows.Cells[2].Text;
        string prodprice = rows.Cells[4].Text;
        string categoryname = rows.Cells[5].Text;
        dt.Rows.Add(prodname,prodprice,categoryname);
    }

    /*Binding the datatable to the new gridview*/
    gridorderlist.DataSource = dt;
    gridorderlist.DataBind();
}

When I was not using usercontrol, I had this gridview defined in ProductList.aspx page and it was working fine. I am confused how to access gridview defined in usercontrol page.

Ritesh Puri
  • 305
  • 2
  • 11
  • I am not able to find an answer to my problem anywhere on stackoverflow. – Ritesh Puri Feb 01 '16 at 19:42
  • From the [documentation for PreviousPage](https://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage.aspx) - "When you use the Transfer method or use cross-page posting to transfer processing from one ASP.NET page to another, the originating page contains request information that might be required for the destination page. You can use the PreviousPage property to access that information. **If the current page is being rendered as a result of a direct request (not a transfer or cross-post from another page), the PreviousPage property contains null.**" – stuartd Feb 01 '16 at 19:56
  • I got the solution after spending some time on this problem. I made a recursive call to find the control and it worked!! – Ritesh Puri Feb 02 '16 at 02:13

0 Answers0