动态添加链接按钮和事件处理程序,处理程序不会触发

时间:2014-12-23 20:54:27

标签: c# asp.net

在后面的代码中我创建了一个链接并添加了一个click事件处理程序:

LinkButton newX = new LinkButton();
newX.Text = "x";
newX.Attributes.Add("problem", problems[p]);
newX.Click += new System.EventHandler(this.RemoveItemFromBucket);

链接在页面上显示正常。但是,当我在调试模式下运行并在处理程序的第一行设置断点时:

public void RemoveItemFromBucket(object sender, EventArgs e)
        {
            string problem = (sender as LinkButton).Attributes["problem"];
...
        }

事件不会发生。

按要求发布我的加载和PreInit代码:

protected void Page_Init(object sender, EventArgs e)
        {
            if (Session["elders"] == null)
            {
                Session["elders"] = (from s in masterDB.SnoMedElders select s).ToList();
            }

            if (Session["snoMed"] == null) {
                Session["snoMed"] = (from s in masterDB.mrconso_SnoMed2014_LimitedToDiseaseBranches select s).ToList();
            }

            if (Session["relations"] == null)                
            {
                Session["relations"] = (from s in masterDB.mrrel_SnoMed2014_LimitedToDiseaseBranches select s).ToList();
            }           
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserRole"] == null)
                Response.Redirect("Login.aspx");

            UnmappedNum.Text =  ((from t in (Session["elders"] as List<SnoMedElder>)
                                select t.SnoMedScui).Distinct().ToList().Count() -
                                (from t in masterDB.tbl_patients_problems_to_snomed_buckets_2014s
                                select t.SnoMedScui).Distinct().ToList().Count() + 600).ToString();
        }

编辑:找出问题所在。问题是我的整个页面都在ajax更新面板中。当我动态添加元素时,它不会被添加到更新面板中,因此整个页面正在重新加载。如何将元素添加到更新面板?

2 个答案:

答案 0 :(得分:0)

你不需要这么低级别。

将该行控件放在aspx中:

<asp:LinkButton runat="server" ID="btnTest" OnClick="btnTest_Click" Text="x"></asp:LinkButton>

...在代码隐藏中:

protected void Page_Load(object sender, EventArgs e)
{
    btnTest.Attributes.Add("problem", problems[p]);
}

protected void btnTest_Click(object sender, EventArgs e)
{
    string problem = (sender as LinkButton).Attributes["problem"];
    //or even
    problem = btnTest.Attributes["problem"]
}

答案 1 :(得分:0)

考虑一下,如果您的网页发回,则没有按钮可以触发事件。您需要在页面oninit或页面加载

中添加链接按钮