主题:GridView动态生成的控件不能触发OnRowCommand事件,且点击控件按钮后,控件的值会消失。

案例,

由于公司需要绑定的数据列顺序是动态生成的,且有的数据列需要绑定Button控件。所以需要动态绑定TemplateField。

问题,不能触发OnRowCommand事件和点击控件按钮后,控件的列值会消失。

不能触发OnRowCommand代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
//protected override void OnInit(EventArgs e)
//{ // TemplateField customField = new TemplateField(); // customField.ShowHeader = true;
// customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "动态添加列");
// GridViewTemplate gvt = new GridViewTemplate(DataControlRowType.DataRow, "lbtn", "Name");
// customField.ItemTemplate = gvt;
// ContactsGridView.Columns.Add(customField);//添加编辑按钮到gridview
//} protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TemplateField customField = new TemplateField(); customField.ShowHeader = true;
customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "动态添加列");
GridViewTemplate gvt = new GridViewTemplate(DataControlRowType.DataRow, "lbtn", "Name");
customField.ItemTemplate = gvt;
ContactsGridView.Columns.Add(customField);//添加编辑按钮到gridview DataTable dt = new System.Data.DataTable();
dt.Columns.Add("data1");
dt.Columns.Add("ContactID"); DataRow dr = dt.NewRow();
dr["data1"] = "test";
dr["ContactID"] = "ContactID";
dt.Rows.Add(dr); DataRow dr2 = dt.NewRow();
dr2["data1"] = "test2";
dr2["ContactID"] = "ContactID";
dt.Rows.Add(dr2); ContactsGridView.DataSource = dt;
ContactsGridView.DataBind();
}
} public class GridViewTemplate : ITemplate
{
public delegate void EventHandler(object sender, EventArgs e);
public event EventHandler eh; private DataControlRowType templateType; private string columnName;
private string controlID; public GridViewTemplate(DataControlRowType type, string colname)
{ templateType = type; columnName = colname; }
public GridViewTemplate(DataControlRowType type, string controlID, string colname)
{
templateType = type;
this.controlID = controlID;
columnName = colname;
} public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
LinkButton lc = new LinkButton();
lc.Text = columnName;
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
LinkButton lbtn = new LinkButton();
lbtn.ID = "id1";
lbtn.Text = "test";
// lbtn.ID = this.controlID;
//if (eh != null)
//{
// lbtn.Click += new System.EventHandler(eh);
//}
// lbtn.DataBinding += new System.EventHandler(lbtn_DataBinding); container.Controls.Add(lbtn); break;
default:
break;
}
} } protected void ContactsGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType==DataControlRowType.DataRow)
{
LinkButton lb = e.Row.FindControl("id1") as LinkButton;
lb.CommandArgument = "";
} } protected void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument); // Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ContactsGridView.Rows[index]; // Create a new ListItem object for the contact in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[].Text) + " " +
Server.HtmlDecode(row.Cells[].Text);
}
}
}
}

后来把数据绑定从Page.IsPostBack移出,是可以触发OnRowCommand事件。但是点击的时候都要重新做GridView的查询,效率会比较差。

  protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ } TemplateField customField = new TemplateField(); customField.ShowHeader = true;
customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "动态添加列");
GridViewTemplate gvt = new GridViewTemplate(DataControlRowType.DataRow, "lbtn", "Name");
customField.ItemTemplate = gvt;
ContactsGridView.Columns.Add(customField);//添加编辑按钮到gridview DataTable dt = new System.Data.DataTable();
dt.Columns.Add("data1");
dt.Columns.Add("ContactID"); DataRow dr = dt.NewRow();
dr["data1"] = "test";
dr["ContactID"] = "ContactID";
dt.Rows.Add(dr); DataRow dr2 = dt.NewRow();
dr2["data1"] = "test2";
dr2["ContactID"] = "ContactID";
dt.Rows.Add(dr2); ContactsGridView.DataSource = dt;
ContactsGridView.DataBind();
}

最终解决方法,

1.用BoundField替代TemplateField方法,代码如下。

 ButtonField adup = new ButtonField();
adup.ButtonType = ButtonType.Link;
adup.HeaderText = "广告上架";
adup.Text = "test";
adup.CommandName = "shangjia";
ContactsGridView.Columns.Add(adup);//添加编辑按钮到gridview

2.重新写OnInit方法。在OnInit上绑定TemplateField,可以触发OnRowCommand事件。

        protected override void OnInit(EventArgs e)
{ TemplateField customField = new TemplateField(); customField.ShowHeader = true;
customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "动态添加列");
GridViewTemplate gvt = new GridViewTemplate(DataControlRowType.DataRow, "lbtn", "Name");
customField.ItemTemplate = gvt;
ContactsGridView.Columns.Add(customField);//添加编辑按钮到gridview
}

2,

动态绑定控件不能触发的估计原因是:

1)用TemplateField动态绑定的控件不是服务器端控件,不在ViewState记录,所以刷新页面后,这些列的值会消失,OnRowCommand事件自然也不会触发。

2)而用BoundField,会记录ViewState,所以刷新页面后,就会触发事件OnRowCommand。

3)在OnInit上绑定控件,首先会初始化绑定控件和事件(OnRowCommand重新绑定了)。这样OnRowCommand事件也会触发。

GridView 动态绑定控件 OnRowCommand事件触发的更多相关文章

  1. file控件change事件触发问题

    最近,项目中需要用到一个图片上传的功能,我用的file控件来选取图片文件,然后利用js读取文件来预览图片,最后再根据用户的操作来决定是否上传文件. 其中碰到了一个奇怪的问题:在选取完第一张图片,并上传 ...

  2. GridView控件RowDataBound事件中获取列字段值的几种途径

    前台: <asp:TemplateField HeaderText="充值总额|账号余额"> <ItemTemplate> <asp:Label ID ...

  3. 关于Asp.net事件,如何在触发子控件的事件时,同步触发父页面的事件

    对页面引用自定义控件后,通过绑定自定义事件,页面绑定子控件的事件,在子控件做了某些修改动作后,如何同步操作父页面的方法:下面我煮了个栗子,同学们可以来尝一尝试一试 a.aspx 引用 UserCont ...

  4. GridView的控件说明[字典]-----方便查询

    GridView 控件以表格的形式显示数据,并提供对数据进行排序,选择,编辑,删除等功能. GridView能够完成的功能具体可以总结如下: 1,通过数据源控件将数据绑定到GridView控件 2,对 ...

  5. WinForm中动态添加控件 出现事件混乱,解决办法记录。

    还是在抢票软件中出的问题,我没点击一个联系人,要生成一排控件,其中有席别combobox这样的下拉框控件,会出现如下图所示的问题:问题描述:在代码中动态创建的控件,事件混乱了,一个控件触发了所有同类型 ...

  6. [DataTable]控件排序事件中用DataView及DataTable排序

    控件排序事件中用DataView及DataTable排序 文章分类:.net编程 在做ASP.NET页面开发时,经常要用到dataset(或者DataTable),绑定到DataGrid或GridVi ...

  7. ASP.NET自定义控件组件开发 第三章 为控件添加事件 前篇

    原文:ASP.NET自定义控件组件开发 第三章 为控件添加事件 前篇 第三章 为控件添加事件 好了,我们之前以前开发一个控件.而且也添加了属性,开发也很规范,但是那个控件还差最后一点:添加事件. 系列 ...

  8. ASP.NET自定义控件组件开发 第三章 为控件添加事件 后篇

    原文:ASP.NET自定义控件组件开发 第三章 为控件添加事件 后篇 第三章 为控件添加事件 后篇 前一篇文章只是简单的说了下事件,但是大家应该方法,在ASP.NET自定义控件中只是简单那么定义事件是 ...

  9. C# winform中自定义用户控件 然后在页面中调用用户控件的事件

    下面是用户控件的代码: using System; using System.Collections.Generic; using System.ComponentModel; using Syste ...

随机推荐

  1. java--creater in windows

    电脑右键--高级--属性--更改环境变量 1.JAVA_HOME  C:\Program Files\Java\jdk1.7.0_04 2. Path                     %JAV ...

  2. PKI

    公钥基础设施(Public Key Infrastructure,简称PKI)是眼下网络安全建设的基础与核心,是电子商务安全实施的基本保障,因此,对PKI技术的研究和开发成为眼下信息安全领域的热点.本 ...

  3. 五 python并发编程之IO模型

    一 IO模型介绍 同步(synchronous) IO和异步(asynchronous) IO,阻塞(blocking) IO和非阻塞(non-blocking)IO分别是什么,到底有什么区别?这个问 ...

  4. Ansible学习 安装

    对于运维人员来说,自动化工具是日常工作中比不可少的.Ansible是一个很好的自动化工具. Ansible默认使用SSH协议管理机器,在管理主机上安装Ansible,管理主机和被管理主机只要安装了py ...

  5. css清除浮动,清除子节点margin溢出问题

    清除浮动 .clearfix:after{ content:”.”; display:block; height:0; clear:both; visibility:hidden; } 清除margi ...

  6. 谭浩强C第四版(p141)16.输出以下图案

    运行结果: * *** ***** ******* ***** *** * Press any key to continue #include<stdio.h> int main() { ...

  7. Python虚拟机类机制之instance对象(六)

    instance对象中的__dict__ 在Python虚拟机类机制之从class对象到instance对象(五)这一章中最后的属性访问算法中,我们看到“a.__dict__”这样的形式. # 首先寻 ...

  8. 在 Amazon AWS 搭建及部署网站:序

    最近玩了把 AWS,实现了服务器的创建.PHP+MySql运行环境.代码部署等.一方面,后面的项目会反复重复这个流程,需要一份手册,另一方面,也给自己一个记录.于是把整个过程和要点整理一下,发到自己的 ...

  9. gulp基本入门

    gulp用于自动化和提高工作流,类似于grunt.gulp适用于nodejs平台.   gulp基础: gulp两个主要的功能是读取想要处理的文件,把处理好的文件放到指定的地方gulp.src()找出 ...

  10. MFC深入浅出读书笔记第二部分2

    第七章  MFC骨干程序 所谓骨干程序就是指有AppWizard生成的MFC程序.如下图的层次关系是程序中常用的几个类,一定要熟记于心. 1 Document/View应用程序 CDocument存放 ...