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

类别:.NET开发 点击:0 评论:0 推荐:
为DataGrid列添加Radio(单选框)列
作者:孟宪会 出自:【孟宪会之精彩世界】 发布日期:2004年7月17日 6点12分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>

本文地址:http://com.8s8s.com/it/it43191.htm