Thursday 10 July 2008

Chaning the ASP.NET Name attribute

This had be frustrated for days - you can change the ID property of a dynamically created control, but you can't change the NAME attribute!

Why do I care? Simple, I wanted to use the ID property for use in JavaScript calls, and the NAME attribute for when I was posting the form data - for example, I wanted two textboxes, one with an ID of 12, but a name of "Name", and another with an ID of 13, but a name of "Age", so that when I submitted the form data, I could get a friendly name for it.

(Before anyone harps on about "the .NET framework uses the NAME property in postbacks" - I do know this, but it is not required in this scenario.)

So, how did I do it? I created a class that inherits from TextBox, and then created an property within it called Name. I then overrided the render method to render the box as I needed it to be done in HTML:


public class MTextBox : TextBox
{
private string _mName;
public string Name
{
get { return _mName; }
set { _mName = value; }
}
//overriden to print name attribute correctly
protected override void Render(HtmlTextWriter writer)
{
string sOutput = "";
//Here you can squirt out your HTML in whatever format you want, e.g. you can
//squirt out the HTML of Name=\" + __mName + "\" etc
writer.Write(sOutput);
}
}


Sorry I can't give a more complete example, but blogger treats the code sample as HTML!!! Contact me if you want the code.

In my application, I can then just do this:

MTextBox textBox = new MTextBox();
textBox.Name = "Something I want it to be!!!";

No comments:

Post a Comment