1.客户端
在客户端来开发,我们主要考虑两个方面的问题
1. 怎么取得GridView所在行的主键值
2. 怎么在选定某个选项,提交给服务器以后,再能保持选项是被选上的
这个问题可以这样解决,我们知道,在客户端,RadioButton的HTML代码是
<input type="radio" id="***" name="**" value="*****" />
我们可以通过一个Literal空间,在GridView的OnRowCreated事件中动态的来控制这个的HTML代码就可以
服务器可以通过Request.Form["**"]来得到该行记录的主键
2.服务器端
其原理也是修改RadioButton的HTML代码.扩张RadioButton类,写成一个服务器控件.
相关代码如下:
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Text;
5using System.Web;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8
9namespace 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 }
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Text;
5using System.Web;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8
9namespace 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 }