[英]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()函數。
問題是,當我單擊鏈接按鈕時,第一次單擊不會觸發genericLinkButton_Click事件。 它會導致回傳,然后如果我再次點擊它,或點擊其他鏈接按鈕之一,genericLinkButton_Click 事件 。
如何確保點擊事件在我的第一次點擊時發生?
謝謝!
僅當GridView獲得數據綁定時,才會觸發RowDataBound
,因此,當您調用gvData.DataBind()
時才觸發。 但是必須在每次回發中再次創建動態創建的控件。
在GridView
動態創建控件的最合適的事件是RowCreated
,它在每次回發時觸發。 請注意,回發時GridViewRow的DataItem
為null
。 因此,與RowDataBound
相對,您無法訪問它的數據源。 但這似乎並沒有必要。
還要注意,您不需要循環RowDataBound
或RowCreated
所有行,因為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.