1

I need to access multiple textboxes on a master page. The textboxes are declared in a separate web control and it won't let me call the names of the textboxes so I can populate them with data. I have multiple textboxes like I said, but for example, when I try to write to txtName it will not let me even though when I click on the Design View it says it is there.

Can anybody help me out?

bbesase
  • 791
  • 4
  • 18
  • 31
  • 1
    possible duplicate of [how to access master page control from content page](http://stackoverflow.com/questions/15573505/how-to-access-master-page-control-from-content-page) – Paddy May 13 '14 at 12:25
  • @Paddy OP explained exactly opposite of that link. Its not duplicate of that. `"The textboxes are declared in a separate web control"`. – Bharadwaj May 13 '14 at 12:32
  • @Bharadwaj - I'm not sure you're right, but even so, there is an answer here that shows how to access content page from the master page: http://stackoverflow.com/questions/4979669/how-to-access-content-page-controls-from-master-page-in-asp-net?rq=1 however, I'm not sure this is really recommended practice. – Paddy May 13 '14 at 12:34
  • @Paddy Yes this question may be duplicate of your second comment link. I just said its not duplicate of the first comment. – Bharadwaj May 13 '14 at 12:37
  • @Bharadwaj Actually, it could be considered a duplicate of the first link also. The answer contained there is relevant to this question, although it is only part of the solution. It is definitely **not** "exactly opposite" like you stated. – mason May 13 '14 at 13:32

1 Answers1

2

Expose the text boxes inside the web control as properties.

In webcontrol.ascx

<asp:TextBox runat="server" id="txtName" />

In webcontrol.ascx.cs

public virtual TextBox TxtName { get {return txtName;} //note capitalization

Then do the same thing in the master page to expose the web control.

In masterpage.master

<uc1:MyWebControl runat="server" id="MyWebControl1" />

In mastermage.master.cs

public virtual MyWebControl myWebControl{get {return myWebControl1;}}

Then make your master page strongly typed from the content page by adding a MasterType directive.

In default.aspx

<%@ MasterType TypeName="MyMasterPageClass" />

Then you can access it from your content page code behind. In default.aspx.cs

Master.myWebControl.TxtName.Text="Hello, world!";

The reason it's necessary to do this is that controls declared on .aspx, .ascx, and .master pages are protected instead of public and there's no way (as of right now) to change them that I'm aware of. So we can use properties to expose these controls as public.

mason
  • 31,774
  • 10
  • 77
  • 121