Category:  ASP.Net 2.0  在asp.net 3.5下需要做一些小的修改

When I have helped people with extending the GridView control shipped with ASP.Net 2.0. I got the idea to write this post.

Some questions that I have seen are about how to extend the GridView control, such as setting the background color of the row when the mouse is moving over a row, turn a row into edit mode when the user has double clicked on a row etc. I wrote about how to set the background color in a previous post. In this post I have added a more functional client side script that will set back the original color of the row when the mouse has left the row.

Here are the changes from my previous post:

I have added two javascript functions, SetNewColor (Will set the color of the row when the user is moving the mouse over it) and SetOldColor (Will set back the original color of the row when the user leaves the row):

<script language=javascript>var _oldColor;function SetNewColor(source){_oldColor = source.style.backgroundColor;source.style.backgroundColor = '#00ff00';}function SetOldColor(source){source.style.backgroundColor = _oldColor;}
</script>

I have also change the RowCreated event to use those new client side functions:

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

e.Row.Attributes.Add("onMouseOver", "SetNewColor(this);");

e.Row.Attributes.Add("onMouseOut", "SetOldColor(this);");

}

You will find the whole example with a lot of other features at the end of this post.

Have you ever wanted to double click on a row and make the row to be changed into an editable mode? Or maybe select a row and press the enter key and do something rational ;)

What I’m going to show you know, is how you can use the client side __doPostBack method to do a postback when you double click on a row.

As you may know the __doPostBack method will be added by ASP.Net 2.0 at runtime, so we don’t need to add the method, we only need to know how to use it. The __doPostBack looks like this:

__doPostBack(eventTarget, eventArgument)

It has two arguments, eventTarget and eventArgument. The eventTarget takes the id of the control which this method is added to as a value.  The eventArgument takes a string with extra information that could be collected on the server side.

To the RowCreated event of the GridView control you can add something like this to make a postback when you click in a row:

e.Row.Attributes.Add("onClick","__doPostBack('GridView1','myEventArgs');");

To get the value from the arguments of the __doPostBack method after a postback has been done, you can use the Request.Form and get the value from two hidden fields that also will be added by ASP.Net:

Request.Form["__EVENTTARGET"]
Request.Form["__EVENTARGUMENT"]

The __EVENTTARGET will have the value of the __doPostBack’s eventTarget argument and the __EVENTAGUMENT will have the value of the evnetArgument.

This is an easy way of using the __doPostBack method to do a postback and also to get the values passed as arguments by the __doPostBack method. There is a more elegant solution for handling postback, and it’s to use the IPostBackEventHandler interface.

When you implement this interface you also need to implement the RaisePostBackEvent method. This method will be automatically called when a postback is done. When you use the IPostBackEventHandler you can use the GetPostBackEventReference method of the Page object to create the __doPostBack method instead of adding it by your self. The RaisePostBackEvent method has one argument of the type string. This argument will have the value of the eventArgument argument of the __doPostBack method.

To implement the IPostBackEventHandler for a Page you use the Implements directive:

<%@ Implements Interface="System.Web.UI.IPostBackEventHandler"%>
或者在页面类的声明处添加 IPostBackEventHandler,当然还得添加implement function 格式如下:
 void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
    {
    }

Instead of adding the __doPostBack by hand, you can use the GetPostBackEventReference method:

public string GetPostBackEventReference(Control control)

public string GetPostBackEventReference(Control control, string eventArgument)

This method has two overloaded methods. The first overloaded method takes one argument with the control that postback is made from. The other method takes two arguments, the control and an argument with extra information as a string. The GetPostBackEventReference will return a generated __doPostBack method for us, where the __doPostBack’s eventTarget argument will have the value of the control’s Id passed as an argument to the GetPostBackEventReference, and the eventArguent argument will have the value of the GetPostBackEventReference’s eventArgument.

Now let’s see how you can use the GetPostBackEventReference method for making a postback when you double click on a row:

e.Row.Attributes.Add("onDblClick", Page.GetPostBackEventReference(this, e.Row.DataItemIndex.ToString()));

The code above is located within the RowCreated event of the GridView control. As you can see in the code, the GetPostBackEventReference is used to return a value for the onDblClick attribute for the rows. The Page object (this) is passed to the GetPostBackEventReference as an argument and the index of the created row is also passed to the method.

When you implement the IPostBackEventHandler, you also need to add the RaisePostBackEvent method to the page. This method will be called after you have double click on a row and the __doPostBack method has been called.

public void RaisePostBackEvent(string eventArgument)

{

Response.Write(eventArgument);

}

Note: There can only be one RasiePostBackEvents method on the Page. If you have used the GetPostBackEventReference for other client side events of the GridView row or for other controls on the page, you have to use the RaisePostBackEvent method’s eventArgument’s value to identify what you should do based on which control that did call the  __doPostBack method.

If you have created a custom render control in .Net, and have added events for the custom control, you are probably already familiar with the IPostBackEventHandler.

Now let’s take a look at the example that will use the IPostBackEvent handler and make a postback when you double click on a row or press on one row and then press en enter key on the keyboard:

<%@ Page Language="C#" %>

<%@ Implements Interface="System.Web.UI.IPostBackEventHandler"%>

<script language=javascript>

var _oldColor;

function SetNewColor(source)

{

_oldColor = source.style.backgroundColor;

source.style.backgroundColor = '#00ff00';

}

function SetOldColor(source)

{

source.style.backgroundColor = _oldColor;

}

</script>

<script runat="server">

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadGridViewProductData();
        }
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

}

private void LoadGridViewProductData()
    {
        DataTable dt = CreateSampleProductData();
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Attributes.Add("onMouseOver", "SetNewColor(this);");
        e.Row.Attributes.Add("onMouseOut", "SetOldColor(this);");
        e.Row.Attributes.Add("onDblClick",  ClientScript.GetPostBackEventReference(this, e.Row.DataItemIndex.ToString()));
        e.Row.Attributes.Add("onKeyDown", "if( event.keyCode == 13 ) " + ClientScript.GetPostBackEventReference(this, "KEYDOWN" + "$" + e.Row.DataItemIndex.ToString()));

}

static DataTable CreateSampleProductData()
    {
        DataTable tbl = new DataTable("Products");

tbl.Columns.Add("ProductID", typeof(int));
        tbl.Columns.Add("ProductName", typeof(string));
        tbl.Columns.Add("UnitPrice", typeof(decimal));
        tbl.Columns.Add("CategoryID", typeof(int));

tbl.Rows.Add(1, "Chai", 18, 1);
        tbl.Rows.Add(2, "Chang", 19, 1);
        tbl.Rows.Add(3, "Aniseed Syrup", 10, 2);
        tbl.Rows.Add(4, "Chef Anton's Cajun Seasoning", 22, 2);
        tbl.Rows.Add(5, "Chef Anton's Gumbo Mix", 21.35, 2);
        tbl.Rows.Add(47, "Zaanse koeken", 9.5, 3);
        tbl.Rows.Add(48, "Chocolade", 12.75, 3);
        tbl.Rows.Add(49, "Maxilaku", 20, 3);

return tbl;
    }

protected virtual void OnDblClick(EventArgs e)
    {
        Response.Write("You double clicked on the row with index: " + ((GridViewSelectEventArgs)e).NewSelectedIndex.ToString());
        GridView1.EditIndex = ((GridViewSelectEventArgs)e).NewSelectedIndex;
    }

protected virtual void OnReturnKeyDown(EventArgs e)
    {
        Response.Write("You press enter on the row with index: " + ((GridViewSelectEventArgs)e).NewSelectedIndex.ToString());
    }

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        LoadGridViewProductData();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        LoadGridViewProductData();
    }

#region IPostBackEventHandler 成员
    // Part of the IPostBackEventHandler interface.

// you must create this method.

void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
    {
        GridViewSelectEventArgs e = null;
        int selectedRowIndex = -1;
        if (!string.IsNullOrEmpty(eventArgument))
        {
            string[] args = eventArgument.Split('$');
            if (string.Compare(args[0], "KEYDOWN", false, System.Globalization.CultureInfo.InvariantCulture) == 0 && args.Length > 1)
            {
                Int32.TryParse(args[1], out selectedRowIndex);
                e = new GridViewSelectEventArgs(selectedRowIndex);
                OnReturnKeyDown(e);
            }
            else
            {
                Int32.TryParse(args[0], out selectedRowIndex);
                e = new GridViewSelectEventArgs(selectedRowIndex);
                OnDblClick(e);
            }
        }
        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert12", "alert('" + eventArgument + "');", true);
    }

#endregion

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="GridView1" Runat="server"  DataKeyNames="ProductID"

AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound"

AlternatingRowStyle-BackColor="#6699ff" RowStyle-BackColor="#ccccff">

<Columns>

<asp:CommandField ShowEditButton="True"></asp:CommandField>

<asp:BoundField ReadOnly="True" HeaderText="ProductID" DataField="ProductID" SortExpression="ProductID"></asp:BoundField>

<asp:BoundField HeaderText="ProductName" DataField="ProductName" SortExpression="ProductName"></asp:BoundField>

<asp:BoundField HeaderText="UnitPrice" DataField="UnitPrice" SortExpression="UnitPrice"></asp:BoundField>

</Columns>

</asp:GridView>

</asp:SqlDataSource>

</div>

</form>

</body>

</html>

In the code above, I have used the event argument to know if someone have double clicked on a row or have pressed the enter key. The code will check if the event argument of the RaisePostBackEvent has the prefix KEYDOWN$. If it do not have the KEYDOWN$ prefix, the OnDblClick method will be called. This method will get the index of the double clicked row from the event argument and use the index to switch the row into its edit mode. When the return key is pressed after a row has been selected, the OnReturnKey method will be called.

转载于:https://www.cnblogs.com/mzwang123/archive/2010/04/10/1709227.html

extend the gridview control相关推荐

  1. 为 GridView 添加一列单选按钮50

    简介 GridView 控件提供多种内置功能.它含有多个显示文本.图像.超链接和按钮的不同字段.它还支持模板的进一步定制.只需轻轻的点击几下鼠标,您即可构造 GridView ,使其每行均可使用按钮进 ...

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

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

  3. GridView 控件编程的事件

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

  4. GridView嵌套GridView

    GridView嵌套可以显示当前选定的父记录组织同时显示所有子记录.例如,你可以用它创建一个完整的按类别组织的产品列表.下一个示例演示如何在单个网格中显示一个完整的分组产品列表,如下图所示:      ...

  5. Scott Mitchell 的ASP.NET 2.0数据教程之一: 创建一个数据访问层

    原文 | 下载本教程中的编码例子 | 下载本教程的英文PDF版 导言 作为web开发人员,我们的生活围绕着数据操作.我们建立数据库来存储数据,写编码来访问和修改数据,设计网页来采集和汇总数据.本文是研 ...

  6. User Profile Data Web Part 读取属性字段

    User Profile Data Web Part   Property Name Display Name UserProfile_GUID Id SID SID ADGuid Active Di ...

  7. 创建自定义排序用户界面

    简介 显示大量已经按类别(不是很多)排序的数据但没有类别分界线,用户很难找到所需要的类别.例如,数据库中只有9个类别(8个不同的类别和1个null),共81种产品.现在用一个GridView列出所有产 ...

  8. 一周最新示例代码回顾 (5/7–5/13)

    回顾上周微软一站式示例代码库最新发布的7篇示例代码: [Sample of May 13th] Show file upload status in ASP.NET 该示例演示如何在ASP.NET网站 ...

  9. ScottGu之博客翻译-LINQ to SQL第三部分,查询数据库 (Part 3 - Querying our Database)

     本贴只为共享知识,更为简洁(即无英文的版本)将会发布在博客堂上,堂主正对此文进行审阅. 希望本贴能对您的LINQ to SQL语言的学习有一定的帮助! 原贴链接: http://weblogs.as ...

最新文章

  1. 基于Grafana+SimpleJson的灵活报表解决方案
  2. 从网上搜索到的虚拟化笔记
  3. idea存在包但是运行项目一直报java.lang.NoClassDefFoundError的问题
  4. 自动输入命令执行_Ubuntu命令行操作-命令简介
  5. Django魔术用法
  6. flask-uploads扩展的使用笔记
  7. 傅里叶变换的终极解释下
  8. Groovy 设计模式 -- null对象模式
  9. (转载)Xcode 4.1/4.2/4.3 免证书(iDP)开发+真机调试+生成IPA全攻略
  10. 数据库基本操作和常用命令
  11. 服务雪崩、服务熔断、服务降级
  12. Oracle中的序列,同义词
  13. 笔记本无线上网设置教程(图文)
  14. vue-3d-model:一个展示三维模型的 Vue 组件
  15. 菜鸟的springboot项目图片上传及图片路径分析
  16. Java使用jdbc连接sqlserver2000与2005的语句差别
  17. 常见数据结构-栈-队列-数组-链表-哈希表
  18. IT方面学习交流群推荐
  19. 【力扣周赛】第347场周赛
  20. layui框架KIT ADMIN后台管理系统模板

热门文章

  1. 博科SAN交换机zone配置(华为SNS系列交换机为例OEM博科)
  2. windows快速关闭有效方法2则
  3. Mysql学习总结(59)——数据库分库分表策略总结
  4. python 不定参数_人生苦短,我学不会Python。——函数中不定长参数的写法
  5. mysql回表查询uuid_MySQL数据库回表与索引
  6. java 多态 显式隐式,Java 构造器中的显式参数和this隐式参数
  7. requests模块报错:Use body.encode('utf-8') if you want to send it encoded in UTF-8.
  8. Java Concurrent--java.util.Concurrent包
  9. 大数据隐私保护技术之脱敏技术
  10. 分模块的maven项目调试时报Source not found的解决办法