簡體   English   中英

在GridView中動態創建的ButtonField上的Onclick事件c#

[英]Onclick Event on a dynamically created ButtonField in GridView c#

我已經在gridview中動態創建了一個列,以使按鈕出現在每一行中。 並試圖使onclick事件起作用。

 ButtonField test = new ButtonField();     
 test.Text = "Details";
 test.ButtonType = ButtonType.Button;
 test.CommandName = "test";
 GridView1.Columns.Add(test);

我的asp基本,一切都會動態添加到gridview中:

<asp:GridView ID="GridView1"  runat="server"> </asp:GridView>

這樣可以很好地附加按鈕,但是我似乎找不到在測試按鈕字段上添加單擊事件的參數。

我試過了:

   void viewDetails_Command(Object sender, GridViewRowEventArgs e)
    {
        if (test.CommandName == "test")
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(),     "alertMessage", "alert('Event works')", true);
        }
    }

這不會運行,因為我認為它沒有綁定任何東西,但是我看不到將這個事件函數綁定到哪里? 僅使用警報消息來測試onclick即可!

任何幫助將是巨大的!

您需要實現RowCommand事件。

標記:

<asp:GridView ID="GridView1"  runat="server" OnRowCommand="GridView1_RowCommand">
</asp:GridView>

旁邊的代碼:

public partial class DynamicGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var test = new ButtonField();
            test.Text = "Details";
            test.ButtonType = ButtonType.Button;
            test.CommandName = "test";
            GridView1.Columns.Add(test);


            GridView1.DataSource = new[] {
                new {Id= 1, Text = "Text 1"  },
                new {Id= 2, Text = "Text 2"  },
            };
            GridView1.DataBind();
        }
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "test")
        {
            ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", "alert('Event works')", true);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM