views:

1371

answers:

4

Is it possible to access an element on a Master page from the page loaded within the ContentPlaceHolder for the master?

I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The ListView currently does not update it's values until the cache is reloaded. We have found that just re-running the ListView.DataBind() will update a listview's contents. We have not been able to run the ListView.DataBind() on a page that uses the Master page.

Below is a sample of what I wanted to do but a compiler error says "PeopleListView does not exist in the current context".

GIS.master - Where ListView resides

...<asp:ListView ID="PeopleListView"...

GISInput_People.aspx - Uses GIS.master as it's master page

GISInput_People.aspx.cs

AddNewPerson()
{
// Add person to table
....

// Update Person List
PeopleListView.DataBind();
...
}

What would be the best way to resolve an issue like this in C# .Net?

A: 

Assuming your master page was named MyMaster:

(Master as MyMaster).PeopleListView.DataBind();

Edit: since PeopleListView will be declared protected by default, you will either need to change this to public, or create a public property wrapper so that you can access it from your page.

bcwood
+7  A: 

I believe you could do this by using this.Master.FindControl or something similar, but you probably shouldn't - it requires the content page to know too much about the structure of the master page.

I would suggest another method, such as firing an event in the content area that the master could listen for and re-bind when fired.

palmsey
+1  A: 

Assuming the control is called "PeopleListView" on the master page

ListView peopleListView = (ListView)this.Master.FindControl("PeopleListView");
peopleListView.DataSource = [whatever];
peopleListView.DataBind();

But @palmsey is more correct, especially if your page could have the possibility of more than one master page. Decouple them and use an event.

HTH

Kev
+1  A: 

One think to remember is the following ASP.NET directive.

<%@ MasterType attribute="value" [attribute="value"...] %>

MSDN Reference

It will help you when referencing this.Master by creating a strongly typed reference to the master page. You can then reference your ListView without needing to CAST.

Adam Carr