簡體   English   中英

動態添加的鏈接按鈕不會在首次點擊時觸發點擊事件-C#

[英]Dynamically added Link Button doesn't fire the on click event on the first click - C#

我正在將鏈接按鈕動態添加到我的Gridview中,如下所示:

protected void addLinks()
{
    foreach (GridViewRow gvr in gvData.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow)
        {
            string itemNbr = gvr.Cells[1].Text;
            LinkButton lb = new LinkButton();
            lb.Text = itemNbr;
            lb.Click += genericLinkButton_Click;
            foreach (Control ctrl in gvr.Cells[1].Controls)
            {
                gvr.Cells[1].Controls.Remove(ctrl);
            }
            gvr.Cells[1].Controls.Add(lb);
        }
    }
}

在我的gridview_RowDataBound事件和Page Load事件if(isPostPack)中調用此addLinks()函數。

問題是,當我單擊鏈接按鈕時,第一次單擊不會觸發genericLinkBut​​ton_Click事件。 它會導致回傳,然后如果我再次點擊它,或點擊其他鏈接按鈕之一,genericLinkBut​​ton_Click 事件

如何確保點擊事件在我的第一次點擊時發生?

謝謝!

僅當GridView獲得數據綁定時,才會觸發RowDataBound ,因此,當您調用gvData.DataBind()時才觸發。 但是必須在每次回發中再次創建動態創建的控件。

GridView動態創建控件的最合適的事件是RowCreated ,它在每次回發時觸發。 請注意,回發時GridViewRow的DataItemnull 因此,與RowDataBound相對,您無法訪問它的數據源。 但這似乎並沒有必要。

還要注意,您不需要循環RowDataBoundRowCreated所有行,因為RowCreated ,這些事件都是 GridView 每一行觸發

protected void gvData_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string itemNbr = e.Row.Cells[1].Text;
        LinkButton lb = new LinkButton();
        lb.Text = itemNbr;
        lb.Click += genericLinkButton_Click;
        foreach (Control ctrl in e.Row.Cells[1].Controls)
        {
            e.Row.Cells[1].Controls.Remove(ctrl);
        }
        e.Row.Cells[1].Controls.Add(lb);
    }
}

我不得不打擾WebForms。

使用Webforms並動態創建控件時,需要先將ID分配給創建的控件,然后再將控件添加到樹中,以使其正常工作。 否則,他們將在頁面生命周期內更改ID,從而導致上述行為。

private int _runningIndex = 0;
protected void gvData_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string itemNbr = e.Row.Cells[1].Text;
        LinkButton lb = new LinkButton();
        lb.ID = "btn" + (_runningIndex++).ToString();
        lb.Text = itemNbr;
        lb.Click += genericLinkButton_Click;
        foreach (Control ctrl in e.Row.Cells[1].Controls)
        {
            e.Row.Cells[1].Controls.Remove(ctrl);
        }
        e.Row.Cells[1].Controls.Add(lb);
    }
}

應該工作。

暫無
暫無

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

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