Is there a way to control how .Net sets the Name
and ID
property of my controls? I have some radio buttons for which I need the name to be the same.
If you omit the runat="server"
attribute from the control's definition, it's name and ID are free for you to set. However, whether or not this is an option depends on your situation.
In the other case, there is no way to really control the Name
and ID
properties for those controls yourself. That is, not until ASP.NET 4.0 (look here for more information) is released.
I have solved this problem in the past by creating a new control that inherits from RadioButton but adds a new GroupName property that is used to render the name of the control. Unfortunately I don't have the code handy, but a quick google came up with something similar on codeproject.
Doesn't work quite like that in .net. They need to be uniquely named because that's how they correlate the radio button back to viewstate. I would ask why you need them to be the same name? If it's because you want the user to only be able to select 1 item out of x, then you want to use the GroupName property.
Yes.
Declare a descendant class from, say, a textbox, which overrides the UniqueID and ClientID properties. Then, use (in this example) MyControls.Textbox instead of the built-in textbox.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyControls
{
public class Textbox : System.Web.UI.WebControls.TextBox
{
public override string ClientID
{
get
{
return ID;
}
}
public override string UniqueID
{
get
{
return ID;
}
}
}
public class Button : System.Web.UI.WebControls.Button
{
public override string ClientID
{
get
{
return ID;
}
}
public override string UniqueID
{
get
{
return ID;
}
}
}
}
Note that you'll need to register your controls in web.config:
<pages>
<controls>
<add tagPrefix="mycontrols" namespace="MyControls" assembly="MyAssembly" />
</controls>
</pages>
Then you can reference them in your markup:
<mycontrols:TextBox id="myID" runat="server"/>