RadioButton in GridView
2008-03-10 16:03 liuqhui 阅读(570) 评论(1) 收藏 举报
在GridView中实现RadioButton的单选功能,主要是从两个方面来考虑
1.客户端
在客户端来开发,我们主要考虑两个方面的问题
1. 怎么取得GridView所在行的主键值
2. 怎么在选定某个选项,提交给服务器以后,再能保持选项是被选上的
这个问题可以这样解决,我们知道,在客户端,RadioButton的HTML代码是
<input type="radio" id="***" name="**" value="*****" />
我们可以通过一个Literal空间,在GridView的OnRowCreated事件中动态的来控制这个的HTML代码就可以
服务器可以通过Request.Form["**"]来得到该行记录的主键
2.服务器端
其原理也是修改RadioButton的HTML代码.扩张RadioButton类,写成一个服务器控件.
相关代码如下:
1.客户端
在客户端来开发,我们主要考虑两个方面的问题
1. 怎么取得GridView所在行的主键值
2. 怎么在选定某个选项,提交给服务器以后,再能保持选项是被选上的
这个问题可以这样解决,我们知道,在客户端,RadioButton的HTML代码是
<input type="radio" id="***" name="**" value="*****" />
我们可以通过一个Literal空间,在GridView的OnRowCreated事件中动态的来控制这个的HTML代码就可以
服务器可以通过Request.Form["**"]来得到该行记录的主键
2.服务器端
其原理也是修改RadioButton的HTML代码.扩张RadioButton类,写成一个服务器控件.
相关代码如下:
1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel;
4
using System.Text;
5
using System.Web;
6
using System.Web.UI;
7
using System.Web.UI.WebControls;
8
9
namespace Utilities
10
{
11
[DefaultProperty("Text")]
12
[ToolboxData("<{0}:GridViewRowSelector runat=\"server\"></{0}:GridViewRowSelector>")]
13
public class GridViewRowSelector : RadioButton
14
{
15
protected override void Render(HtmlTextWriter writer)
16
{
17
GridViewRow row = (GridViewRow)this.NamingContainer;
18
int currentIndex = row.RowIndex;
19
GridView grid = (GridView)row.NamingContainer;
20
this.Checked = (grid.SelectedIndex == currentIndex);
21
this.Attributes.Add("onClick", "javascript:" + Page.ClientScript.GetPostBackEventReference(grid, "Select$" + currentIndex.ToString(), true));
22
base.Render(writer);
23
}
24
25
}
using System;2
using System.Collections.Generic;3
using System.ComponentModel;4
using System.Text;5
using System.Web;6
using System.Web.UI;7
using System.Web.UI.WebControls;8

9
namespace Utilities10
{11
[DefaultProperty("Text")]12
[ToolboxData("<{0}:GridViewRowSelector runat=\"server\"></{0}:GridViewRowSelector>")]13
public class GridViewRowSelector : RadioButton14
{15
protected override void Render(HtmlTextWriter writer)16
{17
GridViewRow row = (GridViewRow)this.NamingContainer;18
int currentIndex = row.RowIndex;19
GridView grid = (GridView)row.NamingContainer;20
this.Checked = (grid.SelectedIndex == currentIndex);21
this.Attributes.Add("onClick", "javascript:" + Page.ClientScript.GetPostBackEventReference(grid, "Select$" + currentIndex.ToString(), true));22
base.Render(writer);23
}24

25
}


浙公网安备 33010602011771号