|
FindControl的使用方法 Control.FindControl (String):在當(dāng)前的命名容器中搜索帶指定 id 參數(shù)的服務(wù)器控件。(有點類似javascript中的getElementById(string)) 簡單的例子: <form id="form1" runat="server"> OnClick="Button1_Click" /> 如果需要獲得頁面中的"TextBox1",代碼中可以使用this.TextBox1來引用,這里我們使用 FindControl: protected void Button1_Click(object sender, EventArgs e) 當(dāng)TextBox1放到其他控件里應(yīng)該怎么查找呢? <div> OnClick="Button1_Click" /> 當(dāng)TextBox1放到Panel里,似乎沒什么影響 TextBox tb=(TextBox)this.FindControl ("TextBox1"),當(dāng)查看生存頁面的HTML代碼是發(fā)現(xiàn),TextBox的ID并沒有改變,所以可以獲得 TextBox1。 <div> 當(dāng)TextBox1放到DataGrid中 <asp:DataGrid ID="dg1" runat="server" OnSelectedIndexChanged="dg1_SelectedIndexChanged"> 這時候this.FindControl("TextBox1")==null,無法獲得TextBox1,查看生成頁面HTML發(fā)現(xiàn),頁 面有多個 <input name="dg1$ctl02$TextBox1" type="text" id="dg1_ctl02_TextBox1" /> <input name="dg1$ctl03$TextBox1" type="text" id="dg1_ctl03_TextBox1" /> TextBox1隱藏了,給DataGrid添加選擇列,通過以下方法獲得被選擇行的TextBox1 protected void dg1_SelectedIndexChanged(object sender, EventArgs e) protected void dg1_EditCommand(object source, DataGridCommandEventArgs e) 如果是在DataGrid的頁眉和頁腳: ((TextBox)this.dg1.Controls[0].Controls[0].FindControl("TextBoxH")).Text = "Head"; 1].FindControl("TextBoxF")).Text = "Footer"; TextBox1在Repeater中 <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" OnItemCommand="Repeater1_ItemCommand"> #DataBinder.Eval(Container.DataItem,"ProductName")%><asp:Button ID="btn" OnClick="btn_click" runat="server" Text="dddd" /><br /> 通過按鈕來獲得TextBox1: protected void btn_click(object sender, EventArgs e) 或者 foreach (RepeaterItem item in this.Repeater1.Items) 自定義控件里的TextBox1 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %> 引用<uc1:WebUserControl ID="WebUserControl1" runat="server" /> 獲取TextBox1: ((TextBox)this.WebUserControl1.FindControl("TextBox1")).Text = "userc"; 模板頁訪問頁面TextBox1 //模板頁的TextBox1 ("TextBox1"); 頁面使用模板頁的TextBox1 //模板頁的TextBox1 ("ContentPlaceHolder1").FindControl("TextBox1"); |
|
|
來自: 悟靜 > 《.net和asp.net》