2012-05-11 89 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

單選按鈕列表不會解決問題,因爲按鈕在形式不同的地方.. :( 由於某種原因,單選按鈕分組仍然不起作用。 –