posts - 615, comments - 10490, trackbacks - 594, articles - 0
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
GridView既强大又好用。为了让它更强大、更好用,我们来写一个继承自GridView的控件。
[索引页]
[源码下载]


扩展GridView控件(7) - 行的指定复选框选中时改变行的样式


作者:webabcd


/*正式版的实现 开始*/

介绍
扩展GridView控件:
行的指定复选框选中的时候改变该行的样式,行的指定复选框取消选中的时候恢复该行的样式

使用方法(设置CheckedRowCssClass复合属性):
CheckBoxID - 模板列中 数据行的复选框ID
CssClass - 选中的行的 CSS 类名


关键代码
js
/*行的指定复选框选中时改变行的样式 开始*/
var yy_sgv_crGridView_pre = new Array(); // cs中动态向其灌数据(GridView内控件ID的前缀数组)
var yy_sgv_crCheckbox_post = new Array(); // cs中动态向其灌数据(数据行的复选框ID的后缀数组)
var yy_sgv_crClassName = ''; // cs中动态向其灌数据(css 类名)

var yy_sgv_crCheckbox = new Array(); // Checkbox数组
var yy_sgv_crCssClass = new Array(); // css 类名数组

function yy_sgv_changeCheckedRowCssClass(obj, cssClass, enableChangeMouseOverCssClass)
{
/// <summary>数据行的指定复选框选中行时改变行的样式</summary>

    
if (yy_sgv_crClassName == '') return;
    
    
var objChk = obj;
    
var objTr = obj;
    
    
do
    
{
        objTr 
= objTr.parentNode;
    }
 
    
while (objTr.tagName != "TR")
    
    
if (objChk.checked)
    
{
        yy_sgv_crCheckbox.push(objChk.id);
        
if (yy_sgv_originalCssClassName != '' && enableChangeMouseOverCssClass)
        
{
            yy_sgv_crCssClass.push(yy_sgv_originalCssClassName);
        }

        
else
        
{
            yy_sgv_crCssClass.push(objTr.className);
        }

            
        objTr.className 
= cssClass;
        
        
if (enableChangeMouseOverCssClass)
            yy_sgv_originalCssClassName 
= cssClass;
    }

    
else
    
{
        
for (var i=0; i<yy_sgv_crCheckbox.length; i++)
        
{
            
if (yy_sgv_crCheckbox[i] == objChk.id)
            
{
                objTr.className 
= yy_sgv_originalCssClassName = yy_sgv_crCssClass[i];
                yy_sgv_crCheckbox.splice(i, 
1);
                yy_sgv_crCssClass.splice(i, 
1);
                
                
break;
            }

        }

    }

}


function yy_sgv_crCheck(e) 
{
/// <summary>单击数据行的复选框时</summary>

    
var evt = e || window.event; // FF || IE
    var obj = evt.target || evt.srcElement  // FF || IE

    yy_sgv_changeCheckedRowCssClass(obj, yy_sgv_crClassName, 
true)
}


function yy_sgv_crListener()
{
/// <summary>监听所有数据行的复选框的单击事件</summary>

    
var elements =  document.getElementsByTagName("INPUT");
    
    
for (i=0; i< elements.length; i++
    
{       
        
if (elements[i].type == 'checkbox') 
        
{
            
for (j=0; j<yy_sgv_crGridView_pre.length; j++)
            
{
                
if (elements[i].id.yy_sgv_startsWith(yy_sgv_crGridView_pre[j]) 
                    
&& elements[i].id.yy_sgv_endsWith(yy_sgv_crCheckbox_post[j]))
                
{
                    yy_sgv_addEvent(elements[i], 'click', yy_sgv_crCheck); 
                    
break;
                }

            }

        }

    }
    
}

   
if (document.all)
{
    window.attachEvent('onload', yy_sgv_crListener)
}

else
{
    window.addEventListener('load', yy_sgv_crListener, 
false);
}

/*行的指定复选框选中时改变行的样式 结束*/

c#
using System;
using System.Collections.Generic;
using System.Text;

using System.Web.UI.WebControls;
using System.Web.UI;

namespace YYControls.SmartGridViewFunction
{
    
/// <summary>
    
/// 扩展功能:行的指定复选框选中时改变行的样式
    
/// </summary>

    public class CheckedRowCssClassFunction : ExtendFunction
    
{
        
/// <summary>
        
/// 构造函数
        
/// </summary>

        public CheckedRowCssClassFunction()
            : 
base()
        
{

        }


        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="sgv">SmartGridView对象</param>

        public CheckedRowCssClassFunction(SmartGridView sgv)
            : 
base(sgv)
        
{

        }


        
/// <summary>
        
/// 扩展功能的实现
        
/// </summary>

        protected override void Execute()
        
{
            
this._sgv.PreRender += new EventHandler(_sgv_PreRender);
        }


        
/// <summary>
        
/// SmartGridView的PreRender事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>

        void _sgv_PreRender(object sender, EventArgs e)
        
{
            
// 构造向数组中添加成员的脚本
            string scriptString = "";
            scriptString 
+= String.Format("yy_sgv_crGridView_pre.push('{0}');", Helper.Common.GetChildControlPrefix(this._sgv));
            scriptString 
+= String.Format("yy_sgv_crCheckbox_post.push('{0}');"this._sgv.CheckedRowCssClass.CheckBoxID);
            scriptString 
+= String.Format("yy_sgv_crClassName = '{0}';"this._sgv.CheckedRowCssClass.CssClass);

            
// 注册向数组中添加成员的脚本
            if (!this._sgv.Page.ClientScript.IsClientScriptBlockRegistered(String.Format("yy_sgv_checkedRowCssClass_{0}"this._sgv.ClientID)))
            
{
                
this._sgv.Page.ClientScript.RegisterClientScriptBlock
                (
                    
this._sgv.GetType(),
                    String.Format(
"yy_sgv_checkedRowCssClass_{0}"this._sgv.ClientID),
                    scriptString,
                    
true
                );
            }

        }

    }

}


/*正式版的实现 结束*/


/*测试版的实现 开始*/

介绍
在GridView中如果每行都有复选框的话,选中了某个复选框则修改该复选框所在行的样式,这是经常要用到的功能,因此我们来扩展一下GridView控件。


控件开发
1、新建一个继承自GridView的类。
/// <summary>
/// 继承自GridView
/// </summary>

[ToolboxData(@"<{0}:SmartGridView runat='server'></{0}:SmartGridView>")]
public class SmartGridView : GridView
{
}

2、新建一个ChangeRowCSSByCheckBox实体类,有两个属性
using System;
using System.Collections.Generic;
using System.Text;

using System.ComponentModel;

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; }
        }


        
private string _cssClassRowSelected;
        
/// <summary>
        
/// 选中行的样式的 CSS 类名
        
/// </summary>

        [
        Description(
"选中行的样式的 CSS 类名"),
        Category(
"扩展"),
        DefaultValue(
""),
        NotifyParentProperty(
true)
        ]
        
public string CssClassRowSelected
        
{
            
get return _cssClassRowSelected; }
            
set { _cssClassRowSelected = value; }
        }


        
/// <summary>
        
/// ToString()
        
/// </summary>
        
/// <returns></returns>

        public override string ToString()
        
{
            
return "ChangeRowCSSByCheckBox";
        }

    }

}


3、在继承自GridView的类中加一个复杂对象属性,该复杂对象就是第2步创建的那个ChangeRowCSSByCheckBox
        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存在一个常量里
using System;
using System.Collections.Generic;
using System.Text;

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();
          }     
       }

        }
        String.prototype.endWith = function(oString){   
            var reg = new RegExp(oString + ""$"");   
            return reg.test(this);
        }  
        //]]>
        </script>
";
    }

}


5、重写OnPreRender方法,注册上面那段客户端脚本
        /// <summary>
        
/// OnPreRender
        
/// </summary>
        
/// <param name="e"></param>

        protected override void OnPreRender(EventArgs e)
        
{
            
base.OnPreRender(e);

            
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函数实现我们想要的功能。
        /// <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 = "";

                            
// 根据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;
                            }


                            
// 给行增加一个yy_selected属性,用于客户端判断行是否是选中状态
                            e.Row.Attributes.Add("yy_selected""false");

                            
// 添加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);

                            
break;
                        }

                    }

                }

            }


            
base.OnRowDataBound(e);
        }



控件使用
添加这个控件到工具箱里,然后拖拽到webform上,设置CheckBoxID属性为模板列的项复选框的ID,CssClassRowSelected属性设置为选中行的样式的CSS类名,则可以实现改变通过CheckBox选中的行的样式的功能。
ObjData.cs
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;

/// <summary>
/// OjbData 的摘要说明
/// </summary>

public class OjbData
{
    
public OjbData()
    
{
        
//
        
// TODO: 在此处添加构造函数逻辑
        
//
    }


    [DataObjectMethod(DataObjectMethodType.Select, 
true)]
    
public DataTable Select()
    
{
        DataTable dt 
= new DataTable();
        dt.Columns.Add(
"no"typeof(string));
        dt.Columns.Add(
"name"typeof(string));

        
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');

            dt.Rows.Add(dr);
        }


        
return dt;
    }

}


Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!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>

/*测试版的实现 结束*/


OK
[源码下载]