A Solution for Rendering Attributes into the Individual Items of a RadioButtonList

D

Dunno

It's long been a problem that in some ASP.NET WebControls developers
have not been able to render custom/additional attributes. The
RadioButtonList is one such control. For instance you'd think that you
could add attributes to the individual radio buttons by iterating
through the RadioButtonLists.Items collection as so:

foreach(ListItem item in rbl.Items)
{
item.Attributes.Add("custom", "custom");
}

No good. They attributes just don't render.

The framework RadioButtonList implements the IRederInfoUser interface.
I found that creating a custom RadioButtonList which derives from the
framework one and also implements this interface can provider a
solution to this problem.

The only method that needs to be implemented is the RenderItem method.
This method is responsible for rendering the individual radio buttons
in the list. Example implementation below.

public class CustomRadioButtonList : RadioButtonList, IRepeatInfoUser
{
void IRepeatInfoUser.RenderItem(ListItemType itemType, int
repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
RadioButton radioButton = new RadioButton();
radioButton.Page = this.Page;
radioButton.GroupName = this.UniqueID;
radioButton.ID = this.ClientID + "_" + repeatIndex.ToString();
radioButton.Text = this.Items[repeatIndex].Text;
radioButton.Attributes["value"] = this.Items[repeatIndex].Value;
radioButton.Checked = this.Items[repeatIndex].Selected;
radioButton.TextAlign = this.TextAlign;
radioButton.AutoPostBack = this.AutoPostBack;
radioButton.TabIndex = this.TabIndex;
radioButton.Enabled = this.Enabled;

// Add custom attributes here.
writer.AddAttribute("custom", "custom");

radioButton.RenderControl(writer);
}
}

It may not be the most elegant way around this problem but it has
worked for me.

Happy Coding.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top