views:

138

answers:

2

This

protected void Page_Load(object sender, EventArgs e) {
    RadioButtonList1.Items.Add(new ListItem("London","1"));
    RadioButtonList1.Items.Add(new ListItem("Paris", "2"));
}

and this

   <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatLayout="Flow">
   </asp:RadioButtonList></div>

produce HTML something like this

   <input id="RadioButtonList1_0" type="radio" name="RadioButtonList1" value="1" />
   <label for="RadioButtonList1_0">London</label>
   <input id="RadioButtonList1_1" type="radio" name="RadioButtonList1" value="2" />
   <label for="RadioButtonList1_1">Paris</label>

but what I really want is this, note the class in the <label> tag.

    <input type="radio" name="Event" id="whatever" value="1" /> 
    <label for="London" class="London">London</label> 
    <input type="radio" name="Event" id="whatever" value="2" /> 
    <label for="Paris" class="Paris">Paris</label>

Can I add a cssClass to the automatically generated <label> tag?

A: 

I'm not an ASP.NET pro, but I do know that you can easily control the presentation of the LABEL's inside your an element with a known ID by using child selectors.

#myElementID LABEL {
  padding: 5px;
}
Alex
Yeah, thanks, that is an idea I may put forward, but designers can be so fussy :D
DrG
+1  A: 

You could inherit from RadioButtonList, like shown here or here.

The last link is probably more in line with what you want.

You should only need to override the RenderItem method, like so:

protected override void 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;

 radioButton.CssClass = InnerCssClass;
 radioButton.Style.Add(HtmlTextWriterStyle.BackgroundColor, this.Items[repeatIndex].Text);

 radioButton.RenderControl(writer);

 // add new label
 Label radioLabel = new Label();
 radioLabel.Text = this.Items[repeatIndex].Text;
 radioLabel.CssClass = this.Items[repeatIndex].Text;
 radioLabel.AssociatedControlID = this.ClientID + "_" + repeatIndex.ToString();
 radioLabel.RenderControl(writer);
}

Note, I have not actually compiled above code, but should be enough to guide you in a proper direction :)

Sune Rievers