为DataGrid列添加Radio(单选框)列
2024-07-21 02:23:11
供稿:网友
经常看到论坛上有人问在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