关闭

为DataGrid列添加Radio(单选框)列

328人阅读 评论(0) 收藏 举报
 

经常看到论坛上有人问在DataGrid中如何实现单选,下面就是一种实现的方法。

查看例子

<%@ Page Language="C#" AutoEventWireup="True" EnableViewState = "true"%> <%@ Import Namespace="System.Data" %> <html> <script runat="server"> DataTable Cart; DataView CartView; ICollection CreateDataSource() { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(string))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double))); for (int i = 0; i < 101; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Item " + i.ToString(); dr[2] = 1.23 * (i+1); dt.Rows.Add(dr); } DataView dv = new DataView(dt); return dv; } void Page_Load(Object sender, EventArgs e) { string js = ""; js+="<script>/r/n"; js+="function ld(){/r/n"; js+="for(i=0;i<document.getElementsByName('RadioName').length;i++)/r/n"; js+="if(document.getElementsByName('RadioName')[i].value=="; js+="document.getElementById('" + rd.ClientID + "').value) "; js+="document.getElementsByName('RadioName')[i].checked=true/r/n"; js+="}/r/n"; js+="window.onload=ld/r/n"; js+="</"+"script>/r/n"; this.RegisterStartupScript("js",js); if (!IsPostBack) { ItemsGrid.DataSource = CreateDataSource(); ItemsGrid.DataBind(); } } void Grid_Change(Object sender, DataGridPageChangedEventArgs e) { ItemsGrid.CurrentPageIndex = e.NewPageIndex; ItemsGrid.DataSource = CreateDataSource(); ItemsGrid.DataBind(); } void btnClick(Object sender, EventArgs e) { if(Request.Form["RadioName"] != null) { rd.Value = Request.Form["RadioName"].ToString(); Label1.Text = "您所选择的是:<font color=red>" + Request.Form["RadioName"].ToString() +"</font>"; } } </script> <body> <form runat="server" id=MM> <input type="hidden" id=rd runat=server/> <asp:DataGrid id="ItemsGrid" runat="server" BorderColor="black" BorderWidth="1" CellPadding="3" AllowPaging="true" AutoGenerateColumns="false" OnPageIndexChanged="Grid_Change"> <HeaderStyle BackColor="#00aaaa"></HeaderStyle> <PagerStyle Mode="NumericPages"></PagerStyle> <Columns> <asp:TemplateColumn> <ItemTemplate> <input type=radio name="RadioName" value='<%# DataBinder.Eval(Container.DataItem, "IntegerValue")%>'/> </ItemTemplate> </asp:TemplateColumn> <asp:BoundColumn HeaderText="数字列" DataField="IntegerValue"/> <asp:BoundColumn HeaderText="字符串列" DataField="StringValue"/> <asp:BoundColumn HeaderText="货币列" DataField="CurrencyValue" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="right"></ItemStyle> </asp:BoundColumn> </Columns> </asp:DataGrid> <br> <asp:Button id="Btn" Text="看你选择的" OnClick="btnClick" runat="server"/> <asp:Label id="Label1" Text="" runat="server"/> </form> </body> </html>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:177640次
    • 积分:3037
    • 等级:
    • 排名:第11493名
    • 原创:107篇
    • 转载:88篇
    • 译文:0篇
    • 评论:28条
    最新评论