如何在GridView中使用RadioButtons单选列,并且获取所选定RadioButton的值。

我们习惯性的做法是在GridView的TemplateField使用RadioButton server control;正如我们在GridView的TemplateField使用checkboxes来完成多选功能一样,我们可以通过遍历行来获取选定checkboxes的值,但RadioButtons的区别之处在于同一页面状态之间只能选取一个RadioButton。那么我们可能会想如何赋予每一个RadioButton不同的名称以取得各自的值,但不幸的是GridView在生成行的同时没有为每一个RadioButton赋予不同名称。该如何解决呢?
我们可以利用HTML RadioButton来巧妙的解决这个问题! 仅仅只需要在GridView的TemplateField使用HTML RadioButton来代替RadioButton server control。

<ASP:GridView ID="GridView1" runat="server"          AutoGenerateColumns="False" BackColor="White"         BorderColor="#CC9966" BorderStyle="None"          BorderWidth="1px" CellPadding="4" Font-Names="Verdana">   <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />

  <Columns>

      <ASP:BoundField DataField="CategoryID" HeaderText="CategoryID" />       

<ASP:BoundField DataField="CategoryName" HeaderText="CategoryName" />     

  <ASP:BoundField DataField="Description" HeaderText="Description" />    

   <ASP:TemplateField HeaderText="Select One">         <ItemTemplate>           <input name="MyRadioButton" type="radio"                      value='<%# Eval("CategoryID") %>' />         </ItemTemplate>       </ASP:TemplateField>   </Columns>   <RowStyle BackColor="White" ForeColor="#330099" />   <SelectedRowStyle BackColor="#FFCC66"            Font-Bold="True" ForeColor="#663399" />   <PagerStyle BackColor="#FFFFCC"            ForeColor="#330099" HorizontalAlign="Center" />   <HeaderStyle BackColor="#990000"            Font-Bold="True" ForeColor="#FFFFCC" /> </ASP:GridView> 在该TemplateField中我们设置了radio,并将其值绑定为我们需要获取的行记录的主键! 当radio button被选定时,我们通过表单对象获取被选定的radio button的值。 string selectedValue = Request.Form["MyRadioButton"]; 试试看,是不是很简单的解决了这个问题!

 

posted on 2017-06-24 17:14  www56  阅读(362)  评论(0编辑  收藏  举报

导航