主题: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. 第七篇:suds.TypeNotFound: Type not found: '(string, http://schemas.xmlsoap.org/soap/encoding/, )'

    想要用Python的suds模块调用webservice地址做自动测试,但是找了很多方法都失败了,最终找到另外一个模块可以作为客户端访问服务器地址. 1.针对非安全的http from zeep im ...

  2. 基于js原生封装的点击显示完整文字

    基于js原生封装的点击显示完整文字 (function(window) { var inner = ''; var showCont_s = function(ele) { this.init.app ...

  3. php扩展开发-变量

    我们在php中用到的变量,在底层的C语言代码里是一个结构体,由四个成员组成typedef struct _zval_struct { zvalue_value value; /* 变量的值,也是一个结 ...

  4. A * B Problem Plus HDU - 1402 (FFT)

    A * B Problem Plus HDU - 1402 (FFT) Calculate A * B.  InputEach line will contain two integers A and ...

  5. BFS:胜利大逃亡

    解题心得: 1.水题,主要主意好一个点就好. 2.注意x.y.z坐标的选取就好. 题目: Ignatius被魔王抓走了,有一天魔王出差去了,这可是Ignatius逃亡的好机会. 魔王住在一个城堡里,城 ...

  6. BFS:CF356C-Compartments

    C. Compartments time limit per test 1 second memory limit per test 256 megabytes input standard inpu ...

  7. [Hdu1693]Eat the Trees(插头DP)

    Description 题意:在n*m(1<=N, M<=11 )的矩阵中,有些格子有树,没有树的格子不能到达,找一条或多条回路,吃完所有的树,求有多少种方法. Solution 插头DP ...

  8. IQueryable与IEnumerable区别

    前者可以延迟加载,即执行完后不马上执行数据库语句,用到再加载.

  9. python之返回状态commands模块

    需要得到命令执行的状态则需要判断$?的值, 在Python中有一个模块commands很容易做到以上的效果. commands.getstatusoutput(cmd)  返回一个元组(status, ...

  10. Android四大组件之服务

    创建一个服务,并与活动绑定 作为安卓四大组件之一的服务,毫无例外也要在manifast中进行注册 新建服务类继承于Service,并覆盖onBind( )方法,用于与活动绑定 public class ...