开发者

Can't get to custom control

I have a custom control on my web form:

<form id="form" runat="server">
      <clc:CustomList 
        ID="myList" 
        runat="server" 
        AddButtonText="add"
        DeleteButtonText="del"
        MoveUpButtonText="up"
        MoveDownButtonText="down"/>
        <div id="test" runat="server"></div>
</form>

I need to get to this control from a static WebMethod. I get the Page object from current HttpContext, but it seems this page object has no contorls (controls count is 0).

[WebMethod]
public static List<CustomListControl.IListItem> GetListItems()
{
    Page page = HttpContext.Current.Handler as Page;

    Control control = null;

    if (page != null)
    {
        control = FindControlRecursive(page, "myList");
    }
    return null;
}

private static Control FindCon开发者_如何学CtrolRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }

    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }

    return null;
}

Any idea why or how to get to my control? Thanks!


You cannot access most properties and methods of the page instance and all controls on the page from within the Page Method. Why? Because page method call is not a postback, which means it doesn't go through the page life cycle, viewstate is not available, and controls are not created. Try to use an UpdatePanel instead.


Try with a standard control inside the page.
If you can find it by ID, then you probably did something wrong registering your custom control (maybe you could provide all the aspx code?).
Also note that the Page class has a builtin FindControl method.

For example, this should work:

<form id="form1" runat="server">
<div>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>

and in the .cs file:

protected void Page_Load(object sender, EventArgs e) {
    var tb = FindControl("TextBox1");
}


Static members can not reference instance references. You will need to pass in a reference to the HttpContext or the page itself from some other instance method in the class. I'd say you'd need to call the static web service with a parameter like this:

protected void Page_Load(object sender, EventArgs e) {
    var tb = GetListItems(this);
}

[WebMethod]
public static List<CustomListControl.IListItem> GetListItems(System.Web.UI.Page page)
{
    var c = null;    

    if (page != null)
    {
        c = page.FindControl("myList");
    }
    return c;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜