views:

58

answers:

1

I have created a class that inherits from RadioButtonList in order to add a GroupName attribute to each list item. (why it was not there already I have no idea).

This works as expected when it is rendered, but does not persist the selected items on postback.

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

    }
}

Does anyone know what I am missing?

Thanks.

A: 

You need to implement the IPostBackDataHandler interface and handle a couple of methods. I'm giving you something I used in a similar control, only I extended the individual RadioButton control and not the list. I added custom Value and GroupName attributes to the button then initialized the value upon postback.

#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

Apologies for a not very optimized code :)

CyberDude
Thanks! I'll give that a try. I have actually now overridden RenderContents instead and got it to work, but this seems cleaner.