Saturday, March 31, 2012

Set Asp.Net web control ID

Hello,

Can someone tell me where can I find a list of the characters which I can use in a web control ID?

Can I for example do:

MyLabel.ID = "Namespace#Control_Type"

Thanks,

Miguel

If you want to be safe, stick with letters and numbers (starting with a letter). Why would you need to worry about other characters?


System.Web.UI documentation for the Control.ID property states only this:

Including spaces in this property will cause an ASP.NET page parser error.

Just for fun, I created 256 labels, each using 1 of the ASCII characters:

for (Int32 counter = 0; counter <= 255; counter++)
{
try
{
Label lbl = new Label();
lbl.ID = "test_ " + Convert.ToChar(counter) + "test";
lbl.Text = "My ID is '" + lbl.ID + "'<br>";
Controls.Add(lbl);
}
catch
{
Label lbl = new Label();
lbl.Text = "ERROR USING CHARACTER '" + Convert.ToChar(counter) + "'<br>";
Controls.Add(lbl);
}
}

It generated no errors. So, I assume you can use any characters you want.

However, you may not use spaces if you declare the label in your HTML markup. For example, this throws an error:

<asp:Label ID="test test" runat="server" />


You, sir, have too much time on your hands. I envy you your four seasons...

Actually, that's a nice little demo, but you probably should consider a few more things. First off, I'd bet that there are other characters that the compiler doesn't like in markup (though of course I'm just assuming). Second, what happens when these controls need to be picked up on postback, or -- more likely to cause a problem -- accessed by client-side code? If nothing else, using chars like underscores, dollar signs, pound signs, and dots are going to confuse the heck out of anyone in the rendered HTML trying to tell what belongs to the control and what part is from the naming container.

Cheers,

0 comments:

Post a Comment