简体   繁体   中英

Access Controls from UserControls in ASPX page

How to Access Controls from UserControls in ASPX page? For example: I want to access gridview which is in usercontrol on ASPX page.

Please help me.

The best way is to provide properties in your UserControl that you can access.

For example:

public GridView UserGrid
{
     get
     {
         return GridView1;
     }
}

But the question is why you need this.

Rule of thumb : Only expose as few as possible. On that way your code will be most robust and readable. So it would eg better to expose it's DataSource rather than the complete GridView .

On the other hand, if you want your page to react on events in your UserControl, it should provide custom events(eg UserDeleted ) that your page then can handle.

Page-UserControl-Commmunication

Because the controls now nothing about eachother at the same level, you have to use the parent page to get it. Try this logic:

  1. Create a property referring to your parent page (the page your control usually is in (might be different because of layering of controls)

  2. Create a property on your page referring to the usercontrol the grid is in, or link to that grid directly.

page.aspx

public UserControl UserGridControl
{
     get;
     set;
}

userControl.ascx

public Page ParentPage
{
     get;
     set;
}

Example call:

Instantiate the properties first. After that, use the following statement to access anything from that control (as an example I used Foo() here, to use as a dummy method, but it seems it was unclear to someone):

otherControl.ascx:

this.ParentPage.UserGridControl.Foo();

EDIT: Want to have a direct code example to be able do it from the page only? See Tim Schmelters answer. If you need a way to call the grid from another user control as well. Use mine.

Try this :

GridView GridView1 = (GridView)WebUserControl1.FindControl("GridView1");

Where WebUserControl1 is ID of use control on .aspx page.

Hope this helps..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM