FINDCONTROL的详细介绍

FindControl的使用方法 Control.FindControl (String):在当前的命名容器中搜索带指定 id 参数的服务器控件。(有点类似javascript中的getElementById(string)) 简单的例子:
TextBox
如果需要获得页面中的"TextBox1",代码中可以使用this.TextBox1来引用,这里我们使用 FindControl: protected void Button1_Click(object sender, EventArgs e) { //Control c = this.FindControl("TextBox1"); //TextBox tb= (TextBox)c; //FindControl返回的是一个Control类型的控件,需要强制类型转化成TextBox类型 TextBox tb=(TextBox)this.FindControl("TextBox1"); this.Label1.Text = tb.Text; } 当TextBox1放到其他控件里应该怎么查找呢?
TextBox
当TextBox1放到Panel里,似乎没什么影响 TextBox tb=(TextBox)this.FindControl ("TextBox1"),当查看生存页面的HTML代码是发现,TextBox的ID并没有改变,所以可以获得 TextBox1。
TextBoxdsd
当TextBox1放到DataGrid中 这时候this.FindControl("TextBox1")==null,无法获得TextBox1,查看生成页面HTML发现,页 面有多个 TextBox1隐藏了,给DataGrid添加选择列,通过以下方法获得被选择行的TextBox1 protected void dg1_SelectedIndexChanged(object sender, EventArgs e) { Control c = this.dg1.Items[this.dg1.SelectedIndex].FindControl("TextBox1"); //Control c = this.dg1.SelectedItem.FindControl("TextBox1"); TextBox tb = (TextBox)c; tb.Text = "TextBox"; } protected void dg1_EditCommand(object source, DataGridCommandEventArgs e) { TextBox tb = (TextBox)e.Item.FindControl("TextBox1"); this.Label1.Text = tb.Text.ToString(); } 如果是在DataGrid的页眉和页脚: ((TextBox)this.dg1.Controls[0].Controls[0].FindControl("TextBoxH")).Text = "Head"; ((TextBox)this.dg1.Controls[0].Controls[this.dg1.Controls[0].Controls.Count - 1].FindControl("TextBoxF")).Text = "Footer"; TextBox1在Repeater中 <% #DataBinder.Eval(Container.DataItem,"ProductName")%>
通过按钮来获得TextBox1: protected void btn_click(object sender, EventArgs e) { //获得按钮 Button btn = (Button)sender; TextBox tb = (TextBox)btn.Parent.FindControl("TextBox1"); tb.Text = "Text"; } 或者 foreach (RepeaterItem item in this.Repeater1.Items) { ((TextBox)item.FindControl("TextBox1")).Text = "Text2"; } 自定义控件里的TextBox1 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %> 引用 获取TextBox1: ((TextBox)this.WebUserControl1.FindControl("TextBox1")).Text = "userc"; 模板页访问页面TextBox1 //模板页的TextBox1 TextBox tbM = (TextBox)this.FindControl("TextBox1"); //页面中的TextBox1 TextBox tbC = (TextBox)this.FindControl("ContentPlaceHolder1").FindControl ("TextBox1"); tbC.Text = tbM.Text; 页面使用模板页的TextBox1 //模板页的TextBox1 TextBox tbM = (TextBox)Master.FindControl("TextBox1"); //本页面的TextBox1 //错误的方法:TextBox tbC = (TextBox)this.FindControl("TextBox1"); TextBox tbC = (TextBox)Master.FindControl ("ContentPlaceHolder1").FindControl("TextBox1"); tbM.Text = tbC.Text.ToString(); 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/maiyude/archive/2010/03/21/5401212.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值