Is ctl00 a constant in ASP NET?
Asked Answered
L

2

9

I need to reference a control in my web app that was generated with the use of a master page. The name of the control in the HTML becomes something like this "ctl00$MainContent$ListBox1". Can I safely do this in the code?

string strName = "ctl00$MainContent$ListBox1";
if (Request.Form[strName] != null)
{
String selectedLanguage = Request.Form[strName];
}

PS. I cannot use ClientID property because this code is called from InitializeCulture() override.

Lietman answered 6/7, 2011 at 3:21 Comment(0)
U
13

You could, but what I do is set the MasterPage ID in my Init():

protected void Page_Init( object sender, EventArgs e ) 
{
    // this must be done in Page_Init or the controls 
    // will still use "ctl00_xxx", instead of "Mstr_xxx"
    this.ID = "Mstr"; 
}
Ultramontanism answered 6/7, 2011 at 3:28 Comment(1)
Dude, I've been banging my head against the wall the whole day today over this and you fixed it with 2 lines of code. THANK YOU!!!Lietman
P
3

ctl00 is the generated ID of your masterpage. In the code-behind, you can set this.ID to whatever you want and any sub-content will be prefixed with that ID instead.

The problem with the code you have above is you're relying on a magic string for a control ID - you need to be careful with this as controls get moved into user controls and master pages become nested. I'm not sure why you can't use ListBox1.SelectedValue?

Propman answered 6/7, 2011 at 3:29 Comment(1)
> I'm not sure why you can't use ListBox1.SelectedValue? >PS. I cannot use ClientID property because this code is called from InitializeCulture() override.Lietman

© 2022 - 2024 — McMap. All rights reserved.