GridView既强大又好用。为了让它更强大、更好用,我们来写一个继承自GridView的控件。
[源码下载]
http://files.cnblogs.com/webabcd/yycontrols.rar
\n
介绍
在GridView中如果每行都有复选框的话,选中了某个复选框则修改该复选框所在行的样式,这是经常要用到的功能,因此我们来扩展一下GridView控件。
\n
GridView既强大又好用。为了让它更强大、更好用,我们来写一个继承自GridView的控件。
[源码下载]
1、新建一个继承自GridView的类。
复制C#代码保存代码/// <summary>
/// 继承自GridView
/// </summary>
[ToolboxData(@"<{0}:SmartGridView runat=\'server\'></{0}:SmartGridView>")]
public class SmartGridView : GridView
{
}
2、新建一个ChangeRowCSSByCheckBox实体类,有两个属性
复制C#代码保存代码using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
\n
namespace YYControls.SmartGridView
{
/// <summary>
/// 通过行的CheckBox的选中与否来修改行的样式
/// 实体类
/// </summary>
[TypeConverter(typeof(ExpandableObjectConverter))]
public class ChangeRowCSSByCheckBox
{
private string _checkBoxID;
/// <summary>
/// 根据哪个ChecxBox来判断是否选中了行,指定该CheckBox的ID
/// </summary>
[
Description("根据哪个ChecxBox来判断是否选中了行,指定该CheckBox的ID"),
Category("扩展"),
DefaultValue(""),
NotifyParentProperty(true)
]
public string CheckBoxID
{
get { return _checkBoxID; }
set { _checkBoxID = value; }
}
\n
private string _cssClassRowSelected;
/// <summary>
/// 选中行的样式的 CSS 类名
/// </summary>
[
Description("选中行的样式的 CSS 类名"),
Category("扩展"),
DefaultValue(""),
NotifyParentProperty(true)
]
public string CssClassRowSelected
{
get { return _cssClassRowSelected; }
set { _cssClassRowSelected = value; }
}
\n
/// <summary>
/// ToString()
/// </summary>
/// <returns></returns>
public override string ToString()
{
return “ChangeRowCSSByCheckBox”;
}
}
}
3、在继承自GridView的类中加一个复杂对象属性,该复杂对象就是第2步创建的那个ChangeRowCSSByCheckBox
复制C#代码保存代码private ChangeRowCSSByCheckBox _changeRowCSSByCheckBox;
/// <summary>
/// 通过行的CheckBox的选中与否来修改行的样式
/// </summary>
[
Description("通过行的CheckBox的选中与否来修改行的样式"),
Category("扩展"),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual ChangeRowCSSByCheckBox ChangeRowCSSByCheckBox
{
get
{
if (_changeRowCSSByCheckBox == null)
{
_changeRowCSSByCheckBox = new ChangeRowCSSByCheckBox();
}
return _changeRowCSSByCheckBox;
}
}
4、新建一个JavaScriptConstant类,把我们要用到的javascript存在一个常量里
复制C#代码保存代码using System;
using System.Collections.Generic;
using System.Text;
\n
namespace YYControls.SmartGridView
{
/// <summary>
/// javascript
/// </summary>
public class JavaScriptConstant
{
internal const string jsChangeRowClassName = @”<script type=”"text/javascript”">
//<![CDATA[
function yy_ChangeRowClassName(id, cssClass, isForce)
{
objRow = document.getElementById(id);
// 如果row的yy_selected属性是\'false\'或者没有yy_selected属性或者要求强制设置
// 那么修改该行的className
if (!objRow.attributes[\'yy_selected\'] || objRow.attributes[\'yy_selected\'].value == ‘false’ || isForce == true)
{
document.getElementById(id).className = cssClass;
}
}
// 设置行的yy_selected属性
function yy_SetRowSelectedAttribute(id, bln)
{
document.getElementById(id).attributes[\'yy_selected\'].value = bln;
}
// 以id结尾的CheckBox执行两次click事件
function yy_DoubleClickCheckBox(id)
{
var allInput = document.all.tags(‘INPUT’);
for (var i=0; i < allInput.length; i++)
{
if (allInput[i].type == ‘checkbox’ && allInput[i].id.endWith(‘checkitem’))
{
// 触发click事件而不执行yy_ClickCheckItem()函数
isInvokeClickCheckItem = false;
allInput[i].click();
isInvokeClickCheckItem = false;
allInput[i].click();
}
}
\n
}
String.prototype.endWith = function(oString){
var reg = new RegExp(oString + “”"”);
return reg.test(this);
}
//]]>
</script>”;
}
}
5、重写OnPreRender方法,注册上面那段客户端脚本
复制C#代码保存代码/// <summary>
/// OnPreRender
/// </summary>
/// <param name=”e”></param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
\n
if ((!String.IsNullOrEmpty(ChangeRowCSSByCheckBox.CheckBoxID)
&& !String.IsNullOrEmpty(ChangeRowCSSByCheckBox.CssClassRowSelected))
|| !String.IsNullOrEmpty(CssClassMouseOver))
{
// 注册实现改变行样式的客户端脚本
if (!Page.ClientScript.IsClientScriptBlockRegistered(“jsChangeRowClassName”))
{
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(),
“jsChangeRowClassName”, JavaScriptConstant.jsChangeRowClassName
);
}
// 注册调用双击CheckBox函数的客户端脚本
if (!Page.ClientScript.IsStartupScriptRegistered(“jsInvokeDoubleClickCheckBox”))
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
“jsInvokeDoubleClickCheckBox”,
@”<script type=”"text/javascript”">yy_DoubleClickCheckBox();</script>”);
}
}
}
6、重写OnRowDataBound以通过调用相关的javascript函数实现我们想要的功能。
复制C#代码保存代码/// <summary>
/// OnRowDataBound
/// </summary>
/// <param name=”e”></param>
protected override void OnRowDataBound(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (!String.IsNullOrEmpty(ChangeRowCSSByCheckBox.CheckBoxID)
&& !String.IsNullOrEmpty(ChangeRowCSSByCheckBox.CssClassRowSelected))
{
foreach (TableCell tc in e.Row.Cells)
{
// 如果发现了指定的CheckBox
if (tc.FindControl(ChangeRowCSSByCheckBox.CheckBoxID) != null)
{
CheckBox chk = tc.FindControl(ChangeRowCSSByCheckBox.CheckBoxID) as CheckBox;
string cssClassUnchecked = “”;
\n
// 根据RowState的不同,取消行的选中后<tr>的不同样式(css类名)
switch (e.Row.RowState)
{
case DataControlRowState.Alternate:
cssClassUnchecked = base.AlternatingRowStyle.CssClass;
break;
case DataControlRowState.Edit:
cssClassUnchecked = base.EditRowStyle.CssClass;
break;
case DataControlRowState.Normal:
cssClassUnchecked = base.RowStyle.CssClass;
break;
case DataControlRowState.Selected:
cssClassUnchecked = base.SelectedRowStyle.CssClass;
break;
default:
cssClassUnchecked = “”;
break;
}
\n
// 给行增加一个yy_selected属性,用于客户端判断行是否是选中状态
e.Row.Attributes.Add(“yy_selected”, “false”);
\n
// 添加CheckBox的click事件的客户端调用代码
string stronclickScript = “”;
if (!String.IsNullOrEmpty(chk.Attributes["onclick"]))
{
stronclickScript += chk.Attributes["onclick"];
}
stronclickScript += “;if (this.checked) “
+ “{yy_ChangeRowClassName(‘” + e.Row.ClientID + “‘, ‘” + ChangeRowCSSByCheckBox.CssClassRowSelected + “‘, true);”
+ “yy_SetRowSelectedAttribute(‘” + e.Row.ClientID + “‘, ‘true’)} “
+ “else {yy_ChangeRowClassName(‘” + e.Row.ClientID + “‘, ‘” + cssClassUnchecked + “‘, true);”
+ “yy_SetRowSelectedAttribute(‘” + e.Row.ClientID + “‘, ‘false’)}”;
chk.Attributes.Add(“onclick“, stronclickScript);
\n
break;
}
}
}
}
\n
base.OnRowDataBound(e);
}
\n
控件使用
添加这个控件到工具箱里,然后拖拽到webform上,设置CheckBoxID属性为模板列的项复选框的ID,CssClassRowSelected属性设置为选中行的样式的CSS类名,则可以实现改变通过CheckBox选中的行的样式的功能。
ObjData.cs
复制C#代码保存代码using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
\n
/// <summary>
/// OjbData 的摘要说明
/// </summary>
public class OjbData
{
public OjbData()
{
//
// TOD 在此处添加构造函数逻辑
//
}
\n
[DataObjectMethod(DataObjectMethodType.Select, true)]
public DataTable Select()
{
DataTable dt = new DataTable();
dt.Columns.Add(“no”, typeof(string));
dt.Columns.Add(“name”, typeof(string));
\n
for (int i = 0; i < 30; i++)
{
DataRow dr = dt.NewRow();
dr[0] = “no” + i.ToString().PadLeft(2, ’0′);
dr[1] = “name” + i.ToString().PadLeft(2, ’0′);
\n
dt.Rows.Add(dr);
}
\n
return dt;
}
}
Default.aspx
复制ASPX代码保存代码<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”Default” %>
\n
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>SmartGridView</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<yyc:SmartGridView ID=”SmartGridView1″ runat=”server” DataSourceID=”ObjectDataSource1″
AutoGenerateColumns=”false”>
<Columns>
<asp:TemplateField>
<itemtemplate>
<%# Container.DataItemIndex + 1 %>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width=”100px”>
<itemtemplate>
<asp:checkbox id=”checkitem” runat=”server” />
</itemtemplate>
</asp:TemplateField>
<asp:BoundField DataField=”no” HeaderText=”序号” />
<asp:BoundField DataField=”name” HeaderText=”名称” />
</Columns>
<ChangeRowCSSByCheckBox CheckBoxID=”checkitem” CssClassRowSelected=”SelectedRow” />
</yyc:SmartGridView>
<asp:ObjectDataSource ID=”ObjectDataSource1″ runat=”server” SelectMethod=”Select”
TypeName=”OjbData”></asp:ObjectDataSource>
</div>
</form>
</body>
</html>
\n
转自【webabcd-.NET】