[Tips]UserControl動態新增時,轉型注意事項

  • 4481
  • 0

[Tips]UserControl動態新增時,轉型注意事項

 

在之前的一篇文章:[ASP.NET]動態Load UserControl – part 2裡面的內容提到如何動態載入與控制UserControl,但之前在轉型上的處理,是有一點瑕疵的。

當初我不知道該怎麼使用UserControl的型別,所以就用中斷點偵錯,去抓UserControl的type到底是什麼。結果在監看式裡面看到的,就是ASP.我的UserControl類別。而程式的執行上也都沒有問題。

先來看看.aspx上的code:

image

code-behind的程式:


    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 3; i++)
        {
            //發行網站會有問題
            ASP.myusercontrol_ascx myUserControl = this.Page.LoadControl("MyUserControl.ascx") as ASP.myusercontrol_ascx;

            //發行網站沒問題
            //MyUserControl myUserControl = this.Page.LoadControl("MyUserControl.ascx") as MyUserControl;
            myUserControl.MyInput.Text = i.ToString();
            this.Panel1.Controls.Add(myUserControl);
        }
    }

編譯與執行程式,都沒啥問題:

image


直到我需要發行網站的時候,發現ASP.我的UserControl類別,會出現參考錯誤的問題:
image 

在經過阿尼哥的好心提醒之下,我才發現原來我之前用錯型別了,ASP.xxxx是run time時的型別,(被發現我是用中斷點去抓型別來用的…)

所以,正確的用法應該是:


    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 3; i++)
        {           
            //發行網站沒問題
            MyUserControl myUserControl = this.Page.LoadControl("MyUserControl.ascx") as MyUserControl;
            myUserControl.MyInput.Text = i.ToString();
            this.Panel1.Controls.Add(myUserControl);
        }
    }

這樣子就程式也能跑,發行網站也沒有問題啦。

 


blog 與課程更新內容,請前往新站位置:http://tdd.best/