GridView中的RadioButton列之间不能互斥

来源:互联网 发布:c语言中 i是什么意思 编辑:程序博客网 时间:2024/06/05 09:47

GridView中的RadioButton列与CheckBox列
GridView拥有大量的内置功能,可以使用不同的默认filed来放置显示诸如TextBox、Buttos等等控件,支持模板是GridView的最大的功能,可以添加额外的、GridView没有的功能,例如RadioButton列。
RadioButton可以让用户只选中一列,而CheckBox可以选中多列。
可能首先想到的GridView中不包含有RadioBox列,是在ItemTemplate中添加RadioBox列,好像不行,这些RadioBox不会相互排斥,最终是用户可以选中多列。
代码段1:
<asp:GridView ID="RadioCheck" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
     <Columns>
         <asp:TemplateField HeaderText="."> 
             <ItemTemplate>
                 <asp:RadioButton ID="btnRadio" runat="server" GroupName="ProductGroup" />
             </ItemTemplate>
         </asp:TemplateField>
         <asp:BoundField DataField="ProductName" HeaderText="ProductName" />
         <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
     </Columns>
</asp:GridView>


设置了GroupName:作用在于让RadioButton在一个组里,产生互斥的效果,只能选中一个,但这样的效果却是能选中多个值,如图Radio1.jpg

也就是说RadioButton没有起到要的作用,没有互斥性,查看源代码,可以发现问题:
<input id="RadioCheck_ctl02_btnRadio" type="radio" name="RadioCheck$ctl02$ProductGroup" value="btnRadio" />
<input id="RadioCheck_ctl03_btnRadio" type="radio" name="RadioCheck$ctl03$ProductGroup" value="btnRadio" />
........
<input id="RadioCheck_ctl10_btnRadio" type="radio" name="RadioCheck$ctl10$ProductGroup" value="btnRadio" />,上面的RadioButton根本没有在一个组里面,GroupName也起不了作用。
解决方法:
  1.移除RadioButton控件,换成Literal控件,ID为RadioButtonMarkup
  2.为GridView的RowCreated事件创建事件,RowCreated事件如下:只要在GridView中新增一行数据,就触发RowCreated事件,不用RowDataBound事件的原因是:只有当数据明确绑定到控件中才引发RowDataBound事件。处理如下:在每一行记录中,编程引用Literal控件,然后在其Text属性里面声明代码,创建RadioButton,name值为ProductGroup,id为RowSelectX,X为index值,value值也为index值。

 

protected void Product_RowCreated(object sender, GridViewRowEventArgs e)
{
  if(e.Row.RowType == DataControlRowType.DataRow)
  {
   Literal output = e.Row.FindControl("RadioButtonMarkup") as Literal;
   output.Text = string.Format(@"<input type="radio" name="ProductGroup"" " + @"id="RowSelector{0}"value="""value{0}",e.Row.RowIndex);
  }
}


当然这是后台使用的方法.
还有一种就是用Javascript脚本事件
.aspx 

    <script type="text/javascript">
    var last=null;
    function judge(obj)
    {
      if(last==null)
      {
         last=obj.id;
      }
      else
      {
        var lo=document.getElementById(last);
        lo.checked=false;
        last=obj.name;
      }
      obj.checked="checked";
    }
    </script>   

.cs 页面里在gridview的 RowDataBound 事件里
   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            RadioButton rb = (RadioButton)e.Row.FindControl("rdoChoose");
            if (rb != null)
            {
                rb.Attributes.Add("onclick", "judge(this)");
            }
        }
    }

注意:如果你有RadioButton同时还有别的JS事件,请一定要追加上,否则就不能正确显示了.我比较偏爱JS这种方法,速度快,而且试过了放在UpdatePannel里也可以.没有过多的复杂测试.

0 0