GridView选中变色离开变为原样
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
a.隔行色(颜色可自定义)
b.点击行任意位置选择行
c.点击已选中行任意位置取消选择
d.选中行变色(颜色可自定义)
e.多选全选功能
f.添加双击响应事件
GridView控件功能非常强大,但在具体应用中很多时候无法满足特殊需求。例如我前段时间做自己网站(网站制作学习吧)。在编写后台管理版块期间。由于是文章站,列表页面会比较多。每个列表显示基本一样,功能包括:单击选择一行;单击已经选择的行实现取消选择;被选中的行变色(颜色可以设置);双击可以实现服务器事件处理。如果每个列表都一一去编写,当然也可以达到目的。但像我这样的懒人就想着去网上找个现成的控件拖拉一下最好。不过找了很多,也下载了很多,都不太合意。不是达不到要求就是功能太过强大界面太过复杂。最后只能硬着头皮自己扩展一个了。
首先新建一个类WebBarGridView(名字随意)并继承自GridView。
public class WebBarGridView : GridView
什么?你说为什么要继续GridView。因为我们要扩展它,添加我们自己想要的新功能。当然你也可以直接继承Control。
接下来为类定义几个公开属性和几个私有变量,代码如下:
private HtmlInputCheckBox cb; //各行前面的多选框
private Button HideButton = new Button();//隐藏按钮用于引发事件,后面会说到[Browsable(true)]
[Category("Appearance")]
[Description("隔行背景色(单号行的背景)")]
public Color SingleBackGroundColor
{
get
{
return ViewState["SingleBackGroundColor"] != null ?
(Color)ViewState["SingleBackGroundColor"] : Color.Empty;
}
set
{
ViewState["SingleBackGroundColor"] = value;
}
[Browsable(true)]
[Category("Appearance")]
[Description("隔行背景色(双号行的背景)")]
public Color DoubleBackGroundColor
{
get
{
return ViewState["DoubleBackGroundColor"] != null ? (Color)ViewState["DoubleBackGroundColor"] : Color.Empty;
}
set
{
ViewState["DoubleBackGroundColor"] = value;
}
}
[Browsable(true)]
[Category("Appearance")]
[Description("选中行背景色")]
public Color ClickBackGroundColor
{
get
{
return ViewState["ClickBackGroundColor"] != null ? (Color)ViewState["ClickBackGroundColor"] : Color.Empty;
}
set
{
ViewState["ClickBackGroundColor"] = value;
}
这里我们用ViewState保存值是为了回发时值还在(保持状态)。属性的做用在Description中都已经说明,这里就不再重复了。
接下来就是各个功能的具体实现了,在实现这些功能之前先初始化GridView并添加全选模板列:protected override void OnInit(EventArgs e)
{
this.HideButton.Click += new EventHandler(this.OnClick);
TemplateField gc = new TemplateField();
gc.HeaderText = "全选";
this.Columns.Insert(0, gc);
base.OnInit(e);
}
好了,现在开始实现具体的功能
一.现在先来看隔行背景色的实现。这里我们重写OnRowDataBound方法代码如下:
protected override void OnRowDataBound(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex != -1)
{
if (e.Row.RowIndex % 2 == 0) { e.Row.BackColor =
this.SingleBackGroundColor; } else { e.Row.BackColor = this.DoubleBackGroundColor; }
}
}
base.OnRowDataBound(e);
}
主要代码:if (e.Row.RowIndex % 2 == 0) { e.Row.BackColor = this.SingleBackGroundColor; } else { e.Row.BackColor = this.DoubleBackGroundColor; }。单行双行设置不同的背景色。
this.SingleBackGroundColor和this.DoubleBackGroundColor就是前面定义的属性。
二.点击行任意位置选择行并改变背景色,点击已选行取消选择
思路:在行上添加单击事件触发Javascrip函数(函数功能:改变行背景色,改变行前面复选框选择状态)