我创建了一个继承自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);
}
}
有谁知道我错过了什么?
感谢。
答案 0 :(得分:0)
您需要实现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
对于未经过优化的代码表示道歉:)