主题: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. gulp的常用插件

    gulp和webpack的差别:https://www.cnblogs.com/lovesong/p/6413546.html var gulp = require('gulp'); var del ...

  2. 【NTT】loj#6261. 一个人的高三楼

    去年看过t老师写这题博客:以为是道神仙题 题目大意 求一个数列的$k$次前缀和.$n\le 10^5$. 题目分析 [计数]cf223C. Partial Sums 加强版.注意到最后的式子是$f_i ...

  3. Maven和Gradle对比(转载)

    转载出处:http://www.cnblogs.com/huang0925 Java世界中主要有三大构建工具:Ant.Maven和Gradle.经过几年的发展,Ant几乎销声匿迹.Maven也日薄西山 ...

  4. 二十二、MySQL 正则表达式

    MySQL 正则表达式 在前面的章节我们已经了解到MySQL可以通过 LIKE ...% 来进行模糊匹配. MySQL 同样也支持其他正则表达式的匹配, MySQL中使用 REGEXP 操作符来进行正 ...

  5. Python周末21天笔记

    模块一: 基础相互据类型之间的相互转换 1. 字符串str 与 列表 list 与字典 dict 以及 元祖tuple的转换 例一: 把字典的key和value的值取出来,按照顺序存入到list中 d ...

  6. A1031 Hello World for U (20)(20 分)

    A1031 Hello World for U (20)(20 分) Given any string of N (>=5) characters, you are asked to form ...

  7. [BZOJ1208]宠物收养所(Splay)

    Description 最近,阿Q开了一间宠物收养所.收养所提供两种服务:收养被主人遗弃的宠物和让新的主人领养这些宠物.每个领养者都希望领养到自己满意的宠物,阿Q根据领养者的要求通过他自己发明的一个特 ...

  8. python单元测试用例

    demo1.py #!/usr/bin/python # encoding: utf-8 def hello(): print "i am in demo1" def add(x, ...

  9. 安装Mysql community server遇到计算机中丢失msvcr120.dll

    一.下载community server版本 Mysql community server版本:https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-5.7 ...

  10. mysql 分组查询前n条数据

    今天去面试,碰到一道面试题: 有一个学生成绩表,表中有 表id.学生名.学科.分数.学生id .查询每科学习最好的两名学生的信息: 建表sql: CREATE TABLE `stuscore` ( ` ...