2012-05-11 88 views
-1

我想组单选按钮与GroupName属性一起.. 它不工作,因为在asp.net而渲染的命名约定的..单选按钮组asp.net

于是,我就继承了单选按钮控制和overrided单选按钮,并创建了自己的控制..

它解决了这个问题,分组,但它不是照顾视图状态的出于某种原因... 所以我所有的单选按钮是是ViewState的少..

这里是我的代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Web.UI.WebControls; 
using System.Web.UI; 

namespace CustomControl 
{ 
    public class GroupRadioButton : RadioButton 
    { 
     public GroupRadioButton() 
      : base() 
     { } 

     protected override void Render(HtmlTextWriter writer) 
     { 
      base.Render(new GroupedRadioButtonTextWriter(writer,this.GroupName)); 
     } 
    } 

    public class GroupedRadioButtonTextWriter : HtmlTextWriter 
    { 
     private string groupName; 

     public GroupedRadioButtonTextWriter(HtmlTextWriter baseWriter, string groupName) : base(baseWriter) 
     { 
      this.groupName = groupName; 
     } 

     public override void AddAttribute(HtmlTextWriterAttribute key, string value) 
     { 
      if (key == HtmlTextWriterAttribute.Name) 
      { 
       base.AddAttribute(key, this.groupName); 
      } 
      else 
      { 
       base.AddAttribute(key, value); 
      } 
     } 
    } 
} 

任何人都可以帮忙吗?

+1

你能解释一下RadioButton的GroupName属性不适合你的方式吗?对我来说就像一个魅力(至少当我使用WebForms时)。您使用的是什么版本的ASP.NET WebForms(我刚刚用4.0重新测试过) – Mirko

+3

您是否试过RadioButtonList?这将创建一组单选按钮。你所需要做的就是将数据源绑定到它。 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.radiobuttonlist.aspx – SCB

回答

1

考虑到RadioButtonList是您应该使用的组件,我认为您通过实施自己的单选按钮来滥用您的时间。

+0

单选按钮列表不会解决问题,因为按钮在形式不同的地方.. :( 由于某种原因,单选按钮分组仍然不起作用。 –