如何在动态创建的gridview中触发按钮事件

本文关键字:按钮 事件 gridview 动态 创建 | 更新日期: 2023-09-27 18:15:38

我有一个gridview与webcontrols(文本框,按钮在页脚)。动态地,我需要通过以下代码创建任意数量的网格视图。但是只创建了一个gridview。还有一个问题是按钮事件没有触发

public void btn_Click(object sender, EventArgs e)
    {
        GridView gv = new GridView();
        gv.ID = sender.ToString();
    }

在类中。如何触发此事件?这是我用来创建gridview的代码。

protected void btnAddGrid_Click(object sender,EventArgs e)
{
    int count = Convert.ToInt32(Session["count"]);
    DataTable dt=(DataTable)ViewState["CurrentTableforCommonDetails"];
    GridView gv = new GridView();
    gv.ID = "GridView" + count;
    gv.AutoGenerateColumns = false;
    if (dt.Rows.Count > 0)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            TemplateField tmpfld = new TemplateField();
            tmpfld.HeaderText = dt.Columns[i].ColumnName.ToString();
            tmpfld.ItemTemplate =new DynamicTemplateField();
            if (i == 0)
            { 
                tmpfld.FooterTemplate = new DynamicTemplateField1();
            }
            gv.Columns.Add(tmpfld);
        }
    }
    gv.Visible = true;
    gv.ShowHeaderWhenEmpty = true;
    gv.ShowFooter = true;
    placegridview.Controls.Add(gv);
    gv.DataSource = dt;
    gv.DataBind();
    count++;
    Session["count"] = count;
}
public class DynamicTemplateField : ITemplate
{
    public void InstantiateIn(System.Web.UI.Control container)
    {
        //define the control to be added , i take text box as your need
        System.Web.UI.WebControls.TextBox txt1 = new System.Web.UI.WebControls.TextBox();
        txt1.ID = "txt1";
        txt1.Width = 50;
        container.Controls.Add(txt1);
    }
}
public class DynamicTemplateField1 : ITemplate
{
    public void InstantiateIn(System.Web.UI.Control container)
    {
        //define the control to be added , i take text box as your need
        System.Web.UI.WebControls.Button btn = new System.Web.UI.WebControls.Button();
        btn.ID = "btn1";
        btn.Click += new EventHandler(btn_Click);
        btn.UseSubmitBehavior = false;
        btn.Text = "Add New";
        container.Controls.Add(btn);
    }
    public void btn_Click(object sender, EventArgs e)
    {
        GridView gv = new GridView();
        gv.ID = sender.ToString();
    }
}

如何在动态创建的gridview中触发按钮事件

这通常涉及跟踪(或维护存储的状态)您拥有动态控件的事实,并在页面生命周期的早期将该控件添加到控件树。下面的示例与您的问题无关,但它演示了如何处理动态控件

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApp.DynamicControls2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ControlsCount = 0;
            }
            else
            {
                for (int i = 0, j = ControlsCount; i < j; i++)
                {
                    CreateControl();
                }
            }
        }
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
        }
        int ControlsCount
        {
            get
            {
                if (ViewState["ControlsCount"] == null)
                {
                    int count = 0;
                    ViewState["ControlsCount"] = count;
                    return count;
                }
                return (int)ViewState["ControlsCount"];
            }
            set
            {
                ViewState["ControlsCount"] = value;
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            CreateControl(true);
        }
        protected void btnCount_Click(object sender, EventArgs e)
        {
        }
        void CreateControl(bool UpdateCount = false)
        {
            TextBox tbx = new TextBox();
            Button btn = new Button() { Text = "Get Time" };
            btn.Click += btn_Click;
            Literal br = new Literal() { Text = "<br/>" };
            var ctls = phContainer.Controls;
            ctls.Add(tbx);
            ctls.Add(btn);
            ctls.Add(br);
            if (UpdateCount) ControlsCount++;
        }
        void btn_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            Control parent = btn.Parent;
            int index = parent.Controls.IndexOf(btn);
            TextBox tbx = parent.Controls[index - 1] as TextBox;
            tbx.Text = DateTime.Now.ToLongTimeString();
        }
    }
}

与此代码关联的webform是:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.DynamicControls2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamic Controls</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
        <asp:Button ID="btnCount" runat="server" Text="Get Count" OnClick="btnCount_Click" />
    </div>
        <br />
        <br />
        <div>
            <asp:PlaceHolder ID="phContainer" runat="server"></asp:PlaceHolder>
        </div>
    </form>
</body>
</html>

您应该相应地调整您的代码以确保这种效果。

如果您想了解诸如跟踪控制树之类的术语,请阅读以下文章系列。http://weblogs.asp.net/infinitiesloop/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_


更新1:

有各种各样的情况,可以根据需要变得复杂。最基本方法的代码如下所示:

Webform (aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApp.DynamicGridViewWithTemplateField.WebForm3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="btn1" runat="server" Text="Clickme" />
    </div>
    </form>
</body>
</html>

后台代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApp.DynamicGridViewWithTemplateField
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            CreateGrid();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!IsPostBack)
                {
                    CreateGrid();
                    ViewState["foo"] = "foo"; //forcing viewstate
                }
            }
        }
        private static DataTable GetNames()
        {
            DataTable tbl = new DataTable();
            tbl.Columns.Add(new DataColumn("Name"));
            List<string> names = new List<string>() { "Arun", "Samit", "Jermy", "John" };
            names.ForEach(x =>
            {
                var row = tbl.NewRow();
                row[0] = x;
                tbl.Rows.Add(row);
            });
            return tbl;
        }
        void CreateGrid()
        {
            GridView gv = new GridView();
            gv.AutoGenerateColumns = false;
            gv.Columns.Add(new BoundField() { 
                HeaderText="Names",
                DataField="Name"
            });
            gv.Columns.Add(new TemplateField()
            {
                ItemTemplate = new TextTemplateField(),
                HeaderText = "Remarks"
            });
            gv.Columns.Add(new TemplateField()
            {
                ItemTemplate = new DropDownTemplateField(),
                HeaderText="Choose option"
            });
            gv.Columns.Add(new TemplateField()
            {
                ItemTemplate = new ButtonTemplateField()                
            });
            gv.RowCommand += (sndr, evt) =>
            {
                if (evt.CommandName == "foo")
                {
                    Control ctrl = (Control)evt.CommandSource;
                    GridViewRow gvRow = (GridViewRow)ctrl.Parent.Parent;
                    var tbx = gvRow.FindControl("tbx1") as TextBox;
                    tbx.Text = DateTime.Now.ToLongTimeString();
                }
            };
            gv.DataSource = GetNames();
            gv.DataBind();
            PlaceHolder1.Controls.Add(gv);
        }
    }
}

ButtonTemplateFieldDropDownTemplateFieldTextTemplateField是简单模板,对应的分别包含一个ButtonDropDownListTextBox。没有什么特别的。

public class DropDownTemplateField : ITemplate
{
    int[] options = new int[] { 1, 2, 3, 4 };
    public void InstantiateIn(Control container)
    {
        DropDownList ddl = new DropDownList();
        ddl.DataSource = options;
        foreach (int value in options)
        {
            ddl.Items.Add(new ListItem(value.ToString(), value.ToString()));
        }
        container.Controls.Add(ddl);
    }
}
public class ButtonTemplateField : ITemplate
{
    public void InstantiateIn(Control container)
    {
        Button btn = new Button();
        btn.CommandName = "foo";
        btn.Text = "Click me";
        container.Controls.Add(btn);
    }
}
public class TextTemplateField : ITemplate
{
    public void InstantiateIn(Control container)
    {
        TextBox tbx = new TextBox();
        tbx.ID = "tbx1";
        container.Controls.Add(tbx);
    }
}