我创建了一个继承自RadioButtonList的类,以便向每个列表项添加一个GroupName属性。(我不知道为什么它已经不在那里了)。
这会在呈现时按预期工作,但不会在回发时保留选定项。
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);
}
}有人知道我错过了什么吗?
谢谢。
发布于 2010-09-06 23:15:16
您需要实现IPostBackDataHandler接口并处理几个方法。我给你提供了一些我在类似控件中使用的东西,只是我扩展了单个RadioButton控件,而不是列表。我向按钮添加了自定义的Value和GroupName属性,然后在回发时初始化值。
#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对一个不是很优化的代码表示歉意:)
https://stackoverflow.com/questions/3652421
复制相似问题