开发者

Control caused the post back

开发者 https://www.devze.com 2023-03-25 03:07 出处:网络
I have a form that contains a dropdownlist, on index changed method,i will call my user control class .cs with parameters choosen by the user, when im putting my code inside the index changed like the

I have a form that contains a dropdownlist, on index changed method,i will call my user control class .cs with parameters choosen by the user, when im putting my code inside the index changed like the code below, it doesnt work, which is a normal behavior:

 protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        ....
        MyUsercontrol c = new MyUSercontrol(....);
        this.panel.controls.add(c);
    } 

thats why i have to put the code inside my onload method, but the thing is how can i know if it is the ddl that caused the post back? is there a propertie? or shoul开发者_C百科d i use page.Request.Params.Get("__EVENTTARGET") technic ? Thanks alot !


If your MyUserControl is really user control, that means .ascx file, you should use this:

Page.LoadControl("~/Controls/MyUserControl.ascx")

instead of creating the instance of the control by calling constructor directly.

protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e) {
        ....
        var c = Page.LoadControl("~/Controls/MyUserControl.ascx");
        this.panel.controls.add(c); 
}

EDIT:

But of course, after every other post back, you will lose this control. So you should also make sure that you will create all dynamic controls during OnLoad event.


set the property autoPostBack=true on the dropdownlist in order for the page to postback

Or use the below function to get the post back control on the page_load

private string GetPostBackControl()
    {
        string retVal = string.Empty;
        try
        {
            string ctrlname = Page.Request.Params.Get("__EVENTTARGET");
            if (ctrlname != null && ctrlname != string.Empty)
            {
                Control ctrl = this.Page.FindControl(ctrlname);
                if (ctrl != null)
                {
                    retVal = ctrl.ID;
                }
            }
        }
        catch (Exception ex) { ManageException(ex, ShowGeneralErrorMessage); }

        return retVal;
    }


Try setting AutoPostBack="True" property of drop down list. After setting this property when you select an item in list it will automatically do the postback and your event ResourceTypesDDL_SelectedIndexChanged will be fired.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号