GridView既强大又好用。为了让它更强大、更好用,我们来写一个继承自GridView的控件。
[索引页]
[源码下载]

扩展GridView控件(3) - 根据按钮的CommandName设置其客户端属性

作者: webabcd

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

介绍
扩展GridView控件:
根据按钮的CommandName设置其客户端属性

使用方法(设置ClientButtons集合属性):
BoundCommandName - 需要绑定的CommandName
AttributeKey - 属性的名称
AttributeValue - 属性的值(两个占位符:{0} - CommandArgument;{1} - Text)
Position - 属性的值的位置

关键代码

using System;
using System.Collections.Generic;
using System.Text;

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

namespace YYControls.SmartGridViewFunction
{
    /// <summary>
    /// 扩展功能:根据按钮的CommandName设置其客户端属性
    /// </summary>
    public class ClientButtonFunction : ExtendFunction
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public ClientButtonFunction()
            : base()
        {

        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sgv">SmartGridView对象</param>
        public ClientButtonFunction(SmartGridView sgv)
            : base(sgv)
        {

        }

        /// <summary>
        /// 扩展功能的实现
        /// </summary>
        protected override void Execute()
        {
            this._sgv.RowDataBoundCell += new SmartGridView.RowDataBoundCellHandler(_sgv_RowDataBoundCell);
        }

        /// <summary>
        /// SmartGridView的RowDataBoundCell事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="gvtc"></param>
        void _sgv_RowDataBoundCell(object sender, GridViewTableCell gvtc)
        {
            TableCell tc = gvtc.TableCell;

            // TableCell里的每个Control
            foreach (Control c in tc.Controls)
            {
                // 如果控件继承自接口IButtonControl
                if (c is IButtonControl)
                {
                    // 从用户定义的ClientButtons集合中分解出ClientButton
                    foreach (ClientButton cb in this._sgv.ClientButtons)
                    {
                        // 如果在ClientButtons中绑定了该按钮的CommandName
                        if (((IButtonControl)c).CommandName == cb.BoundCommandName)
                        {
                            // 替换占位符{0}-CommandArgument;{1}-Text
                            string attributeValue = 
                                String.Format(
                                    cb.AttributeValue,
                                    ((IButtonControl)c).CommandArgument,
                                    ((IButtonControl)c).Text);
                            
                            // 设置按钮的客户端属性
                            YYControls.Helper.Common.SetAttribute(
                                (IAttributeAccessor)c, 
                                cb.AttributeKey, 
                                attributeValue, 
                                cb.Position);

                            break;
                        }
                    }
                }
            }
        }
    }
}
/*正式版的实现 结束*/
/*测试版的实现 开始*/

介绍
给按钮增加单击弹出确认框的功能是经常要用到的,我们一般是通过在RowDataBound事件里编码的方式实现,麻烦,所以扩展一下。

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

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

2、新建一个ConfirmButton类,有两个属性

    /// <summary>
    /// ConfirmButton 的摘要说明。
    /// </summary>
    [ToolboxItem(false)]
    [TypeConverter(typeof(ConfirmButtonConverter))]
    public class ConfirmButton
    {
        private string _commandName;
        /// <summary>
        /// 按钮的CommandName
        /// </summary>
        public string CommandName
        {
            get { return this._commandName; }
            set { this._commandName = value; }
        }

        private string _confirmMessage;
        /// <summary>
        /// 确认框弹出的信息
        /// </summary>
        public string ConfirmMessage
        {
            get { return this._confirmMessage; }
            set { this._confirmMessage = value; }
        }
    }

3、新建一个继承自CollectionBase的类ConfirmButtons

    /// <summary>
    /// ProjectGroups 的摘要说明。
    /// 注意要继承自CollectionBase
    /// </summary>
    [
    ToolboxItem(false),
    ParseChildren(true)
    ]
    public class ConfirmButtons : CollectionBase
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public ConfirmButtons()
            : base()
        {
        }

        /// <summary>
        /// 实现IList接口
        /// 获取或设置指定索引处的元素。
        /// </summary>
        /// <param name="index">要获得或设置的元素从零开始的索引</param>
        /// <returns></returns>
        public ConfirmButton this[int index]
        {
            get
            {
                return (ConfirmButton)base.List[index];
            }
            set
            {
                base.List[index] = (ConfirmButton)value;
            }
        }

        /// <summary>
        /// 实现IList接口
        /// 将某项添加到 System.Collections.IList 中。
        /// </summary>
        /// <param name="item">要添加到 System.Collections.IList 的 System.Object。</param>
        public void Add(ConfirmButton item)
        {
            base.List.Add(item);
        }

        /// <summary>
        /// 实现IList接口
        /// 从 System.Collections.IList 中移除特定对象的第一个匹配项。
        /// </summary>
        /// <param name="index">要从 System.Collections.IList 移除的 System.Object</param>
        public void Remove(int index)
        {
            if (index > -1 && index < base.Count)
            {
                base.List.RemoveAt(index);
            }
        }
    }

4、新建一个继承自ExpandableObjectConverter的类ConfirmButtonConverter

    /// <summary>
    /// 类型转换器
    /// </summary>
    public class ConfirmButtonConverter : ExpandableObjectConverter
    {
        /// <summary>
        /// 返回值能否将ConfirmButton类型转换为String类型
        /// </summary>
        /// <param name="context"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return true;
            }
            return base.CanConvertTo(context, destinationType);
        }

        /// <summary>
        /// 将ConfirmButton类型转换为String类型
        /// </summary>
        /// <param name="context"></param>
        /// <param name="culture"></param>
        /// <param name="value"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture,
            object value, Type destinationType)
        {
            if (value != null)
            {
                if (!(value is YYControls.SmartGridView.ConfirmButton))
                {
                    throw new ArgumentException(
                        "无效的ConfirmButton", "value");
                }
            }

            if (destinationType.Equals(typeof(string)))
            {
                if (value == null)
                {
                    return String.Empty;
                }
                return "ConfirmButton";
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }

5、在继承自GridView的类中加一个复杂对象属性,该复杂对象就是第3步创建的那个ConfirmButtons

        private ConfirmButtons _confirmButtons;
        /// <summary>
        /// 确认按钮集合
        /// </summary>
        [
        PersistenceMode(PersistenceMode.InnerProperty),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        Description("确认按钮集合,确认按钮的CommandName和提示信息"),
        Category("扩展")
        ]
        public virtual ConfirmButtons ConfirmButtons
        {
            get
            {
                if (_confirmButtons == null)
                {
                    _confirmButtons = new ConfirmButtons();
                }
                return _confirmButtons;
            }
        }

6、重写OnRowDataBound实现单击命令按钮弹出确认框的功能。主要是给按钮增加一个客户端的onclick事件。

        /// <summary>
        /// OnRowDataBound
        /// </summary>
        /// <param name="e"></param>
        protected override void OnRowDataBound(GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (this._confirmButtons != null)
                {
                    // GridViewRow的每个TableCell
                    foreach (TableCell tc in e.Row.Cells)
                    {
                        // TableCell里的每个Control
                        foreach (Control c in tc.Controls)
                        {
                            // 如果控件继承自接口IButtonControl
                            if (c.GetType().GetInterface("IButtonControl") != null && c.GetType().GetInterface("IButtonControl").Equals(typeof(IButtonControl)))
                            {
                                // 从用户定义的ConfirmButtons集合中分解出ConfirmButton
                                foreach (ConfirmButton cb in _confirmButtons)
                                {
                                    // 如果发现的按钮的CommandName在ConfirmButtons有定义的话
                                    if (((IButtonControl)c).CommandName == cb.CommandName)
                                    {
                                        // 增加确认框属性
                                        ((IAttributeAccessor)c).SetAttribute("onclick", "return confirm('" + cb.ConfirmMessage + "')");
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            base.OnRowDataBound(e);
        }

控件使用
添加这个控件到工具箱里,然后拖拽到webform上,设置其ConfirmButtons属性即可。CommandName是命令按钮的CommandName属性;ConfirmMessage是弹出的确认框所显示的文字。
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>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            &nbsp;
            <yyc:SmartGridView ID="SmartGridView1" runat="server" AutoGenerateColumns="false"
                DataSourceID="ObjectDataSource1">
                <Columns>
                    <asp:BoundField DataField="no" HeaderText="序号" SortExpression="no" />
                    <asp:BoundField DataField="name" HeaderText="名称" SortExpression="name" />
                    <asp:ButtonField CommandName="ConfirmTest" Text="确认按钮测试" />
                </Columns>
                <ConfirmButtons>
                    <yyc:ConfirmButton ConfirmMessage="确认删除吗?" CommandName="ConfirmTest"></yyc:ConfirmButton>
                </ConfirmButtons>
            </yyc:SmartGridView>
            <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="Select"
                TypeName="OjbData"></asp:ObjectDataSource>
        </div>
    </form>
</body>
</html>
/*测试版的实现 结束*/

OK
[源码下载]

扩展GridView控件(3) - 根据按钮的CommandName设置其客户端属性相关推荐

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

    GridView既强大又好用.为了让它更强大.更好用,我们来写一个继承自GridView的控件. [索引页] [×××] 扩展GridView控件(7) - 行的指定复选框选中时改变行的样式 作者:w ...

  2. 扩展GridView控件——为内容项添加拖放及分组功能

    引言 相信大家对GridView都不陌生,是非常有用的控件,用于平铺有序的显示多个内容项.打开任何WinRT应用或者是微软合作商的网站,都会在APP中发现GridView的使用."Tiles ...

  3. 扩展GridView控件(2) - 复合排序和排序状态提示

    GridView既强大又好用.为了让它更强大.更好用,我们来写一个继承自GridView的控件. [索引页] [源码下载] 扩展GridView控件(2) - 复合排序和排序状态提示 作者:webab ...

  4. 上接扩展GridView控件(10) - 自定义分页样式

    5.重写OnRowCreated以实现自定义分页样式 /// <summary>                  /// OnRowCreated                  // ...

  5. html中设置控件大小,css按钮的大小设置

    css按钮的大小设置方法:首先创建一个HTML示例文件:然后在body中通过button标签创建一个按钮:最后使用"font-size"属性来设置按钮大小即可. 本文操作环境:wi ...

  6. GridView控件详解

    GridView是ASP.NET 1.x的DataGrid控件的后继者.它提供了相同的基本功能集,同时增加了大量扩展和改进.如前所述,DataGrid(ASP.NET 2.0仍然完全支持)是一个功能非 ...

  7. 自定义的GridView控件源代码

    简单地扩展GridView控件的功能.扩展的功能有:当前页/共几页,首页  上一页  下一页  末页  go[]ok 而且还能把gridview导入到excel中. Code   1namespace ...

  8. asp.net GridView控件的列属性

    BoundField 默认的数据绑定类型,通常用于显示普通文本 CheckBoxField 显示布尔类型的数据.绑定数据为TRUE时,复选框数据绑定列为选中状态:绑定数据为FALSE时,则显示未选中状 ...

  9. GridView 控件编程的事件

    我把MSDN的例子全部提出来一个一个看.这样容易更好理解 PageIndexChanged 在单击某一页导航按钮时,但在 GridView 控件处理分页操作之后发生.此事件通常用于以下情形:在用户定位 ...

  10. 【ASP.NET】第八课——GridView 控件的编辑功能优化,GridView控件中嵌套DropDownList控件

    知识点:掌握 GridView 的编辑.高亮显示的功能 .GridView控件中嵌套DropDownList控件获取数据源. [ASP.NET]第七课--数据绑定和 GridView 控件的使用 重点 ...

最新文章

  1. 一球从M米高度自由下落,每次落地后返回原高度的一半,再落下。 它在第N次落地时反弹多高?共经过多少米? 保留两位小数...
  2. ubuntu16搭建z-blog博客
  3. 数字电路是如何搭建的
  4. docker 安装oracle_rancher安装oracle 11g
  5. Django从理论到实战(part34)--聚合函数
  6. AUTOSAR从入门到精通100讲(四十六)-CANoe工具使用-实现CAN通道的收、发、录、回放报文
  7. MySQL的错误:No query specified
  8. 英语学习笔记2019-11-15
  9. AR9331中Linux内核启动中与IRQ中断相关的文件
  10. mysql还要mysqldump的备份文件到指定数据库
  11. oracle中的表怎样保存,怎样保存excel 表格数据库中-如何将excel表格更新oracle数据库中数据...
  12. 使用priority_queue实现Dijkstra
  13. mysql一键部署_一键部署----mysql5.6--jue
  14. pyqt5 qwidget有父类窗口如何设置模态_实战PyQt5: 024-Qt Designer进阶一
  15. 彻底清除微软拼音输入法
  16. 什么是android应用程序未安装,应用程序未安装,教您安卓系统应用程序未安装怎么解决...
  17. 谷歌浏览器和火狐浏览器永久禁用缓存【一劳永逸的解决方式】
  18. 《神雕瞎驴》,金庸看后哭了^-^
  19. ERP流程二 实体类大全
  20. updater-script命令详解教你写刷机脚本

热门文章

  1. 计算机管理用房设置要求,党政机关办公用房管理系统解决方案
  2. 【ADS学习笔记(二)——ADS初次仿真】
  3. 苹果macOS 13 Ventura 5K原生动态壁纸
  4. vsftpd 安装及简单配置
  5. 每日新闻丨三大运营商公布5G套餐;华为云领跑中国DevOps云服务市场;致远互联科创板上市...
  6. Linux : 终端命令整理
  7. linux终端命令大全(完善中)
  8. LaTeX 语法教程
  9. 设计师不可错过的2022年设计类网站大搜集,素材 教程 案例 全都有
  10. 【Rust日报】 2019-05-22:Mozilla图像团队发布WebRender MVP