關於findcontrol()方法的一個研究

來源:互聯網
上載者:User

今天要給repeater做上一個checkbox,然後能做到圈選反選,本來很簡單的事,但是我發現了findcontrol方法的一個好的優點。
前台Binder 方法如下:
<asp:Repeater ID="Repeater1" runat="server">
                <ItemTemplate><asp:CheckBox ID="ch" runat="server" /></ItemTemplate>
            </asp:Repeater>

後台代碼如下:
foreach (Control c in this.Repeater1.Controls)
        {
            CheckBox check = (CheckBox)c.FindControl("ch");
            if (check != null)
            {
                check.Checked = true;
            }

        }

好像細看沒什麼神奇,但是,從html代碼中,你看到repeater產生的html代碼如下:
<INPUT id=Repeater1_ctl00_ch type=checkbox name=Repeater1$ctl00$ch>
<INPUT id=Repeater1_ctl03_ch type=checkbox name=Repeater1$ctl03$ch>
地球人都知道伺服器端的id到了用戶端就極有可能在asp.net產生控制項樹的時候被asp.net自動重新命名,為的防止一個頁面多個重複id,那為什麼在回傳的時候後台又能夠通過findcontrol("ch")來擷取到呢?這就是asp.net為我們作的工作了。

順便說說3種獲得repeater中的checkbox 的方法:
foreach( RepeaterItem item in this.Repeater1.Items )
   {
    HtmlInputCheckBox check = (HtmlInputCheckBox)item.FindControl("cbDelete1");
    if( check != null )
    {
     check.Checked = true;
    }
   } 

for (int i=0;i<this.Repeater1.Items.Count;i++)
   {
    HtmlInputCheckBox check = (HtmlInputCheckBox)this.Repeater1.Items[i].FindControl("cbDelete1");
    if( check != null )
    {
     check.Checked = true;
    }
   }

foreach (Control c in this.Repeater1.Controls)
   {
    HtmlInputCheckBox check = (HtmlInputCheckBox)c.FindControl("cbDelete1");
    if( check != null )
    {
     check.Checked = true;
    }

   }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.