[转]如何GridView里使用单选按钮
在GridView里做单选按钮,我用了三种方法
先介绍第一种方法:在GridView的模版列里加服务器端控件RadioButton,使用js控制单选使用模版列里加RadioButton
控制单选的js,在这里,我使用了遍历页面上所有控件的方法,加入了条件,就是加粗那个判断,只控制GridView1里id是RadioButton1生成的单选按钮这种办法需要绑定客户端事件
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//给每个RadioButton1绑定setRadio事件
try
{
((RadioButton)e.Row.FindControl("RadioButton1")).Attributes.Add("onclick", "setRadio(this)");
}
catch (Exception)
{ }
}
取值的方法就是遍历GridView的每一行,取选中的控件
protected void Button1_Click(object sender, EventArgs e)
{
//使用模版列里加RadioButton
Label1.Text = "";
foreach (GridViewRow gvr in GridView1.Rows)
{
try
{
if (((RadioButton)gvr.FindControl("RadioButton1")).Checked)
{
Label1.Text = "当前选中第" + Convert.ToString(gvr.RowIndex + 1) + "个";
break;
}
}
catch (Exception)
{ }
}
if (Label1.Text.Length == 0)
{
Label1.Text = "没有选中项";
}
}
这种方法,在客户端和服务器端都使用了遍历。

