65.9K
CodeProject 正在变化。 阅读更多。
Home

带单选按钮和单选功能的 DATAGRID

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.61/5 (8投票s)

2006年11月9日

CPOL
viewsIcon

73709

downloadIcon

106

本文档介绍了如何创建一个带有单选按钮且只能单选的 Data Grid。

引言

在 Web 应用程序的 Data Grid 行项目中放置单选按钮,并且每次只能选择一个单选按钮是一个常见的问题。我遇到过许多解决方案,例如,创建一个允许其子控件的 “id” 属性更改的自定义 Data Grid,或者我甚至找到了一些免费的“RowSelector”控件,它们允许在 Data Grid 中进行单选按钮选择。但这些解决方案会带来大量的处理开销或过于复杂。我认为使用一些 JavaScript 来完成这项任务的解决方案将非常有用。

以下 JavaScript 代码将允许实现 Data Grid 中单选按钮的预期任务。

<script  language="javascript">
function SelectOne(rdo,gridName)
{
/* Getting an array of all the "INPUT" controls on the form.*/
all=document.getElementsByTagName("input");
 for(i=0;i<all.length;i++)
 {
  if(all[i].type=="radio")/*Checking if it is a radio button*/
  {
/*I have added '__ctl' ASP.NET adds '__ctl' to all 
    the controls of DataGrid.*/
   var count=all[i].id.indexOf(gridName+'__ctl'); 
   if(count!=-1)
   {
    all[i].checked=false;
   }
  }
 }
 rdo.checked=true;/* Finally making the clicked radio button CHECKED */
}
</script>

下面是 DataGrid

<table width="100%">
 <tr>
     <td align="center">
    <b>
        <u>DATAGRID WITH RADIO BUTTON AND SINGLE SELECTION</u>
    </b>
     </td>
 </tr>
    <tr>
     <td align="center">
      <asp:DataGrid Runat="server" ID="dg" AutoGenerateColumns="False"
     BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
    BackColor="White" CellPadding="4" 
    OnItemDataBound="dg_onItemDataBound"
    OnPageIndexChanged="dg_onPageIndexChanged" PageSize="5"
    AllowPaging="True" GridLines="None" Width="25%">
       <FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
       <SelectedItemStyle Font-Bold="True"
    ForeColor="#663399" BackColor="#FFCC66"/>
       <ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
       <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC"
     BackColor="#990000"/>
       <Columns>
        <asp:TemplateColumn>
         <ItemTemplate>
          <input type="radio" runat="server" id="rdo" 
        onclick="SelectOne(this,'dg')" VALUE="rdo" />
     </ItemTemplate>
        </asp:TemplateColumn>
        <asp:BoundColumn DataField="_Id" HeaderText="Id"/>
        <asp:BoundColumn DataField="_Name" HeaderText="Name"/>
       </Columns>
       <PagerStyle HorizontalAlign="Center" 
    ForeColor="#330099" BackColor="#FFFFCC"/>
      </asp:DataGrid>
  </td>
 </tr>
</table>
祝您阅读愉快!
© . All rights reserved.