簡體   English   中英

重新創建動態創建的按鈕

[英]Recreate dynamically created buttons

我知道ASP.NET頁面的生命周期,但我很困惑。 我這里有從數據庫記錄創建按鈕的代碼。 單擊它們后,它們消失了,沒有觸發任何代碼。 :(我知道我必須在Page_Init中重新創建它們,但我不知道如何。請幫助!這是我的代碼:

        try
        {
            con.Open();
            SqlDataReader myReader = null;
            SqlCommand myCom = new SqlCommand("select ID,client from tposClient where CardNo='" + cNo + "'", con);

            myReader = myCom.ExecuteReader();

            Panel panel1 = new Panel();
            panel1.Style["text-align"] = "Center";
            panel1.Style["background"] = "blue";
            div_login.Visible = false;

            while (myReader.Read())
            {
                string b = myReader["client"].ToString();
                string id = myReader["ID"].ToString();

                Button btn = new Button();
                btn.Text = b;
                btn.ID = id;
                btn.Style["width"] = "100px";
                btn.Click += new EventHandler(btn_Click);
                panel1.Controls.Add(btn);

                panel1.Controls.Add(new LiteralControl("<br />"));
                form1.Style.Add("display", "block");
                form1.Controls.Add(panel1);
            }
        }
        catch (Exception k)
        {
            Console.WriteLine(k.ToString());
        }
        finally
        {
            cmdselect.Dispose();
            if (con != null)
            {
                con.Close();
            }
        }

您應該將Button放在ListView控件中,該控件將針對您返回的每個結果重復執行。 以這種方式使用按鈕將容易得多,並且您不必處理在每個Postback上重新創建控件的問題。

創建一個帶有按鈕的ListView

<asp:ListView ID="lv1" runat="server" OnItemDataBound="lv1_ItemDataBound">
    <ItemTemplate>
        <asp:Button ID="btn1" runat="server" Text="my Text />
    </ItemTemplate>
</asp:ListView>

進行數據訪問之后,創建一個Dictionary<string, string>來保存每個按鈕的文本和ID,然后可以使用它們來綁定ListView

//Your data access code
Dictionary<string, string> buttonIdsWithText = new Dictionary<string, string>();
while(myReader.Read())
{
    string buttonText = myReader["client"].ToString();
    string buttonId = myReader["ID"].ToString();
    buttonIdsWithText.Add(buttonId, buttonText);
}
lv1.DataSource = buttonIdsWithText;
lv1.DataBind();

創建一個ItemDataBound事件處理程序,以便您可以設置按鈕文本

public void lv1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType != ListViewItemType.DataItem)
    {
        return;
    }

    KeyValuePair<string, string> idWithText = 
        (KeyValuePair<string, string>)e.Item.DataItem;
    Button myButton = e.Item.FindControl("btn1") as Button;
    myButton.Text = idWithText.Value;
}

如果需要將按鈕ID專門設置為從數據庫中獲得的ID(並且您正在使用.NET 4),則可以將按鈕的ClientIDMode設置為“ Static ,並將ID設置為所需的ID。

暫無
暫無

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

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