2009-12-02 45 views
0

使用RadioButtonLists時可以控制標籤嗎?

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

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

生成HTML像這樣

<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> 

,但我真正想要的就是這個,注意在<label>標籤類。

<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> 

我可以一個的CssClass添加到自動生成的<label>標籤?

回答

1

你可以從RadioButtonList繼承,如所示herehere

最後一個鏈接可能更符合你的要求。

您應該只需要重寫RenderItem方法,像這樣:

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); 
} 

注意,我並沒有實際上面的代碼編譯,但應該足以指導您正確的方向:)

0

我不是ASP.NET專業版,但我確實知道,您可以使用子選擇器輕鬆控制LABEL在具有已知ID的元素中的呈現。

#myElementID LABEL { 
    padding: 5px; 
} 
+0

是的,謝謝,這是我可能提出的想法,但設計師可以如此挑剔:D – inspite

相關問題