FindControl的使用方法 Control.FindControl (String):在当前的命名容器中搜索带指定 id 参数的服务器控件。(有点类似javascript中的getElementById(string)) 简单的例子: <form id="form1" runat="server"> OnClick="Button1_Click" /> 如果需要获得页面中的"TextBox1",代码中可以使用this.TextBox1来引用,这里我们使用 FindControl: protected void Button1_Click(object sender, EventArgs e) 当TextBox1放到其他控件里应该怎么查找呢? <div> OnClick="Button1_Click" /> 当TextBox1放到Panel里,似乎没什么影响 TextBox tb=(TextBox)this.FindControl ("TextBox1"),当查看生存页面的HTML代码是发现,TextBox的ID并没有改变,所以可以获得 TextBox1。 <div> 当TextBox1放到DataGrid中 <asp:DataGrid ID="dg1" runat="server" OnSelectedIndexChanged="dg1_SelectedIndexChanged"> 这时候this.FindControl("TextBox1")==null,无法获得TextBox1,查看生成页面HTML发现,页 面有多个 <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》