2010-09-06 62 views
0

我已經創建了一個繼承自RadioButtonList的類,以便爲每個列表項添加一個GroupName屬性。 (爲什麼它不在那裏,我不知道)。將組名添加到RadioButtonList中的項目

這種方式在渲染時按預期工作,但不會在回發中保留所選項目。

public class GroupedRadioButtonList : RadioButtonList 
{ 
    [Bindable(true), Description("GroupName for all radio buttons in list.")] 
    public string GroupName 
    { 
     get; 
     set; 
    } 

    protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, System.Web.UI.HtmlTextWriter writer) 
    { 
     RadioButton radioButton = new RadioButton(); 
     radioButton.Page = this.Page; 
     radioButton.GroupName = this.GroupName; 
     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.RenderControl(writer); 

    } 
} 

有沒有人知道我失蹤了?

謝謝。

回答

0

您需要實現IPostBackDataHandler接口並處理幾個方法。我給你的東西我用在類似的控制,只有我擴展了個人RadioButton控制,而不是名單。我向該按鈕添加了自定義ValueGroupName屬性,然後在回發時初始化該值。

#region IPostBackDataHandler Members 
    void IPostBackDataHandler.RaisePostDataChangedEvent() 
    { 
     OnCheckedChanged(EventArgs.Empty); 
    } 

    bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) 
    { 
     bool result = false; 
     //check if a radio button in this button's group was selected 
     string value = postCollection[GroupName]; 
     if ((value != null) && (value == Value)) //was the current radio selected? 
     { 
      if (!Checked) //select it if not already so 
      { 
       Checked = true; 
       result = true; 
      } 
     } 
     else //nothing or other radio in the group was selected 
     { 
      if (Checked) //initialize the correct select state 
      { 
       Checked = false; 
      } 
     } 
     return result; 
    } 
#endregion 

道歉的不是很優化的代碼:)

+0

謝謝!我會試一試。我現在實際上已經重寫了RenderContents,並使其工作,但這看起來更清晰。 – Craig 2010-09-06 16:04:39

+0

2年和我有同樣的問題。我使用與@Craig完全相同的代碼,但是當我設置'radioButton.GroupName = this.GroupName;''LoadPostData'永遠不會被觸發。只有'radioButton.GroupName = this.UniqueID;'纔會被觸發。有任何想法嗎?? – GFoley83 2013-07-01 21:57:20