由于ASP.NET中的RadioButton控件在DataGrid 模板列中不能达到分组的效果,但是基于ASP.NET良好的编程性的前提下,要达到这个效果并不是很难.以前有见过一些朋友采用HTML控件可以达到这一效果,这里有我采用ASP.NET自带的RadioButton控件来编写的效果,虽然生成出来的JS不怎么漂亮,但也有一定的好处.
在ASPX页面中加入以下代码:
<asp:datagrid class="grid" id="DataGrid1" runat="server" Width="720px" AllowSorting="True" AllowPaging="True"
PageSize="3" AutoGenerateColumns="False" BackColor="White">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:RadioButton ID="radGroup" runat="server"></asp:RadioButton>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="CUSTNO" HeaderText="客户"></asp:BoundColumn>
<asp:BoundColumn DataField="SBNO" HeaderText="单号"></asp:BoundColumn>
<asp:BoundColumn DataField="ORDERNO" HeaderText="订单号码"></asp:BoundColumn>
<asp:BoundColumn DataField="LOTNO" HeaderText="批号"></asp:BoundColumn>
<asp:BoundColumn DataField="GETPCS" HeaderText="匹数">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="GETKG" HeaderText="数量">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundColumn>

</Columns>
<PagerStyle Mode="NumericPages"></PagerStyle>
</asp:datagrid>
在CS代码中加入以下代码段:
private void DataGrid1_PreRender(object sender, System.EventArgs e)

{
ArrayList arylstRadio=new ArrayList();

if(this.DataGrid1.Items.Count>0 & !Page.IsPostBack)

{
RadioButton radFirst=this.DataGrid1.Items[0].Cells[0].Controls[1] as RadioButton;

radFirst.Checked=true;
}
if(this.DataGrid1.Items.Count>0)

{
String series="";

for(int i=0;i<this.DataGrid1.Items.Count;++i)

{
RadioButton rad=this.DataGrid1.Items[i].Cells[0].Controls[1] as RadioButton;
if(rad!=null)
arylstRadio.Add(rad.ClientID);
}

//为前面的RadioButton添加客户端事件达到在整个Grid中实现单选的效果
for(int i=0;i<this.DataGrid1.Items.Count;++i)

{
RadioButton rad=this.DataGrid1.Items[i].Cells[0].Controls[1] as RadioButton;
series=this.DataGrid1.Items[i].Cells[2].Text;

string aa="document.all('"+this.hlDetail.ClientID+"').href='"+"Detail.aspx?_series="+series+"&JBNO="+tbxJobCard.Text+"';";
aa+="document.all('"+this.HyperLink3.ClientID+"').href='"+"Detail.aspx?_series="+series+"&JBNO="+tbxJobCard.Text+"';";

rad.Attributes.Add("onclick",getRadioId(rad.ClientID,arylstRadio)+aa);
}
}
}

//得到其它RadioButton的索引
private string getRadioId(string currentClientId,ArrayList ary,int index)

{
String ClientIdList="";

foreach(object obj in ary)

{
if(obj.ToString()!=currentClientId)

{
ClientIdList+="document.all('"+obj.ToString()+"').checked=false;";
}
}
//其中采用(Hidden)hidIndex保存index(选中项的索引)
return ClientIdList+ "document.all('" + this.hidIndex.ClientID + "').value=" + index + ";";
}
以上示例供学习ASP.NET的朋友参考.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)