Can I call page_load event of usercontrol before page_load event of aspx page?

北城以北 提交于 2019-12-04 05:54:34

问题


The question is straight forward.Can I call page_load of usercontrol before page_load of aspx page?

EDIT

Its not possible to call the child's page_load event before parent's page_load.

I have this aspx class called just4test for testing puropse. Its aspx code is:

<body>
  <form id="form1" runat="server">
  <uc1:lcont ID="lcont1" runat="server" />
  <div>

  </div>
  </form>

As you can see it is using a usercontrol file.

And its code behind is :

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        lcont1.my_tv_SelectedNodeChanged(sender, e);
    }
 }

Now the usercontrol is:

public partial class lcont : System.Web.UI.UserControl
{
sql_con sq = new sql_con();
protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
        bind_data();
    }
}

public void mytry()
    {
        Console.WriteLine("helo");
    }
public void bind_data()
{
    main_cat mcobj = new main_cat();
    List<main_cat> mclist = new List<main_cat>();
    mclist = mcobj.get_mcatlist();

    populatetree(mclist);
}

public void populatetree(List<main_cat> mytnode)
{
    TreeNode parentnode = null;
    foreach (main_cat mc in mytnode)
    {
        parentnode = new TreeNode(mc.Cname, mc.Cid.ToString());
        foreach (sub_cat sc in mc.scl)
        {
            TreeNode cnode = new TreeNode(sc.PRODUCT, sc.SID.ToString());
            parentnode.ChildNodes.Add(cnode);
        }
        parentnode.Collapse();
        my_tv.Nodes.Add(parentnode);
    }
}

public void my_tv_SelectedNodeChanged(object sender, EventArgs e)
{
    TreeView tv = sender as TreeView;
    //TreeView tv = new TreeView();
    var selectedN = tv.SelectedNode;

    if (selectedN.Parent != null)
    {
        var id = tv.SelectedNode.Value;
        var name = tv.SelectedNode.Text;
        //Session["mySvar"] = id;

        ScriptManager.RegisterStartupScript(this, this.GetType(), "nething", "show("+id+")", true);
    }
    else
    {
        //Response.Redirect("test.aspx");
    }


}

}

I need to call the function my_tv_SelectedNodeChanged(sender, e); of usercontrol before the page_load of just4test page and i have done so.But when i run the program it says

Object reference not set to an instance of an object.

What should i do?


回答1:


Page_Load no, but OnInit occures before. Depends on your actual problem, you can move your logic there.

Or call a public method of the User control before you do anything else in the Parent Page Page_Load event

See Page Life Cycle



来源:https://stackoverflow.com/questions/24751494/can-i-call-page-load-event-of-usercontrol-before-page-load-event-of-aspx-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!