Asp.Net頁面添加控制項方法和原理

來源:互聯網
上載者:User

因為項目需要,如何在Asp.Net頁面添加控制項。

其實部落格員都給出了答案,本文只是做了一些測試和總結

Asp.Net頁面添加控制項問題的關鍵就是原本在頁面載入的時候所有的控制項初始化操作都應該完成,動態載入將載入的過程延遲到了事件被觸發之後,因此在頁面回傳後, 因為會有一次新的頁面載入過程,顯然這時候動態載入的控制項是不存在的,但是使用者預期的答案是顯示已經載入的資訊。這時候如果可能我們最好在載入的過程中進 行控制項的重新載入和資料繫結。

 

 按照一般人的思維想法,都會使用

 public void AddTextBoxs()
    {
        TableRow tr = new TableRow();
        TableCell tc1 = new TableCell();
        TextBox t = new TextBox();
        t.ID = "tb" + Table1.Rows.Count;
        tc1.Controls.Add(t);
        TableCell tc2 = new TableCell();
        DropDownList dpl = new DropDownList();
        dpl.ID = "dpl" + Table1.Rows.Count;
        for (int i = 0; i < 10; i++) dpl.Items.Add(i.ToString());
        tc2.Controls.Add(dpl);
        tr.Cells.Add(tc1);
        tr.Cells.Add(tc2);
        Table1.Rows.Add(tr);
}

然後在一個button裡添加click事件

 protected void Button1_Click(object sender, EventArgs e)
    { 
        AddTextBoxs();
    }

程式測試,頁面是可以產生相關的控制項。

問題出在,如果你再按其他按鈕會發現你添加的動態控制項消失啦,更別提如何取值拉?

根據尋找答案,原因是每次按鈕後,頁面重新post一次,必須重新添加相關的控制項  所以在formload event中添加

    protected void Page_Load(object sender, EventArgs e)
    {

        if (ViewState["Count"] != null)
        {
            for (int i = 0; i < Convert.ToInt16(ViewState["Count"]); i++)
                AddTextBoxs();
           }
    }

   protected void Button1_Click(object sender, EventArgs e)
    {
        AddTextBoxs();
        if (ViewState["Count"] == null) AddButton();
        ViewState["Count"] = Convert.ToInt16(ViewState["Count"]) + 1;
    }

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.