在DataGrid中使用单选框
其实现步骤如下
1. 在DataGrid中添加一列模板列,在模板列中加入单选框,但是不能用
RadioButton,这样就不能达到效果,其HTML代码为:
<
asp:datagrid
id
="DataGrid1"
runat
="server"
Width
="100%"
AutoGenerateColumns
="False"
>
< AlternatingItemStyle Height ="22px" BackColor ="#F8F8F8" ></ AlternatingItemStyle >
< ItemStyle HorizontalAlign ="Center" Height ="22px" BackColor ="White" ></ ItemStyle >
< HeaderStyle HorizontalAlign ="Center" Height ="25px" CssClass ="lab" BackColor = "#B4D6EE" ></ HeaderStyle >
< Columns >
< asp:TemplateColumn HeaderText ="选择" >
< HeaderStyle Width ="5%" ></ HeaderStyle >
< ItemTemplate >
< input type =radio name ="RadioName"
value = '<%# DataBinder.Eval(Container.DataItem, "Serial")% > '/>
</ ItemTemplate >
</ asp:TemplateColumn >
</ Columns >
</ asp:datagrid >
< AlternatingItemStyle Height ="22px" BackColor ="#F8F8F8" ></ AlternatingItemStyle >
< ItemStyle HorizontalAlign ="Center" Height ="22px" BackColor ="White" ></ ItemStyle >
< HeaderStyle HorizontalAlign ="Center" Height ="25px" CssClass ="lab" BackColor = "#B4D6EE" ></ HeaderStyle >
< Columns >
< asp:TemplateColumn HeaderText ="选择" >
< HeaderStyle Width ="5%" ></ HeaderStyle >
< ItemTemplate >
< input type =radio name ="RadioName"
value = '<%# DataBinder.Eval(Container.DataItem, "Serial")% > '/>
</ ItemTemplate >
</ asp:TemplateColumn >
</ Columns >
</ asp:datagrid >
2.数据源绑定
单选框的Value值应该设置为可以唯一标识该记录的值,比如主键、序号。这边举例绑定的是序号,其字段为:Serial。再获取数据后,手动添加序号列,其代码如下:
if
(dtSource
!=
null
&&
dtSource.Rows.Count
>
0
)
{
dtSource.Columns.Add("Serial",Type.GetType("System.String"));
for(int i = 0;i<dtSource.Rows.Count;i++)
{
dtSource.Rows[i]["Serial"] = i.ToString();
}
}
// 绑定数据
DataGrid1.DataSource = dtSource;
DataGrid1.DataBind();
{
dtSource.Columns.Add("Serial",Type.GetType("System.String"));
for(int i = 0;i<dtSource.Rows.Count;i++)
{
dtSource.Rows[i]["Serial"] = i.ToString();
}
}
// 绑定数据
DataGrid1.DataSource = dtSource;
DataGrid1.DataBind();
3.获取选中记录
该函数返回选中记录的序号,如果返回值是-1表示没有选中的记录。
private
int
GetSerial()
{
if(Request.Form["RadioName"] != null)
{
try
{
return Convert.ToInt32(Request.Form["RadioName"].ToString());
}
catch
{
return -1;
}
}
else
{
return -1;
}
}
{
if(Request.Form["RadioName"] != null)
{
try
{
return Convert.ToInt32(Request.Form["RadioName"].ToString());
}
catch
{
return -1;
}
}
else
{
return -1;
}
}