asp.net (C#) 解決動態新增按鈕click事件無法觸發問題

asp.net因為有生命週期的關係,所有的controls需在page_init 中建立否則在重整頁面時將會消失

以下為應用gridview創建動態欄位及按鈕時的實作

CS.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    
    <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
       
    <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
        runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" >
    </asp:GridView>
    </form>
</body>
</html>

CS.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class CS : System.Web.UI.Page
{
    public string strName
    {
        get { return (ViewState["Name"] == null) ? "" : (string)ViewState["Name"]; }
        set { ViewState["Name"] = value; }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        //CODE PLACEHOLDER
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);     
        CreateTemplate();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
           
    }
    private void CreateTemplate()
    {
        if (strName!="")
        {
            GridView1.Columns.Clear();
            BoundField bfield = new BoundField();
            bfield.HeaderText = "Name";
            bfield.DataField = "Name";
            GridView1.Columns.Add(bfield);

            TemplateField tfield = new TemplateField();
            tfield.HeaderText = "Country";
            GridView1.Columns.Add(tfield);

            tfield = new TemplateField();
            tfield.HeaderText = "View";
            GridView1.Columns.Add(tfield);
            this.BindGrid();

        }
        //GridView1.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        strName = "Jay";
        CreateTemplate();
    }
  
    private void BindGrid()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        
        dt.Rows.Add(1, strName, "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox txtCountry = new TextBox();
            txtCountry.ID = "txtCountry";
            txtCountry.Text = (e.Row.DataItem as DataRowView).Row["Country"].ToString();
            e.Row.Cells[1].Controls.Add(txtCountry);

            LinkButton lnkView = new LinkButton();
            lnkView.ID = "lnkView";
            lnkView.Text = "View";
            lnkView.Click += ViewDetails;
            lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
            e.Row.Cells[2].Controls.Add(lnkView);


        }
    }

    protected void ViewDetails(object sender, EventArgs e)
    {
        LinkButton lnkView = (sender as LinkButton);
        GridViewRow row = (lnkView.NamingContainer as GridViewRow);
        string id = lnkView.CommandArgument;
        string name = row.Cells[0].Text;
        string country = (row.FindControl("txtCountry") as TextBox).Text;
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + " Name: " + name + " Country: " + country + "')", true);
    }
 

    }


預覽圖

 

參考資料

http://couldbedone.blogspot.tw/2007/06/dynamically-created-controls-in-aspnet.html