首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在RadioButtonList中向项目添加GroupName

在RadioButtonList中向项目添加GroupName
EN

Stack Overflow用户
提问于 2010-09-06 23:00:09
回答 1查看 2.4K关注 0票数 0

我创建了一个继承自RadioButtonList的类,以便向每个列表项添加一个GroupName属性。(我不知道为什么它已经不在那里了)。

这会在呈现时按预期工作,但不会在回发时保留选定项。

代码语言:javascript
复制
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);

    }
}

有人知道我错过了什么吗?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-09-06 23:15:16

您需要实现IPostBackDataHandler接口并处理几个方法。我给你提供了一些我在类似控件中使用的东西,只是我扩展了单个RadioButton控件,而不是列表。我向按钮添加了自定义的ValueGroupName属性,然后在回发时初始化值。

代码语言:javascript
复制
#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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3652421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档