0

我有两个用户控件,其中一个我有一个文本框,我需要从注册在同一页面中的第二个用户控件中检索其值。我怎样才能做到这一点?我知道以下行是错误的..但我记得是这样的。

TextBox myText = (TextBox)FindControl["mycontrol"] as TextBox;
4

2 回答 2

2

如果需要从第一个控件访问第二个控件的值

var textBox = this.Page.FindControl("SecondUserControl")
                  .FindControl("tbCardNumber") as TextBox;

其中SecondUserControl是页面中给出的 id,tbCardNumber是第二个控件中 TextBox 给出的 id

如果您尝试从页面访问 TextBox

var textBox = SecondUserControl1.FindControl("SecondUserControl")
                                .FindControl("tbCardNumber") as TextBox;

其中SecondUserControl1是控件的 ID,您可以在后面的代码中访问它。

但是,您可以通过属性公开文本框的值

public string TextBoxValue
{
   get
    {
        return tbCardNumber.Text;
    }
}

但是如果您通过另一个用户控件访问它,您仍然需要 FindControl 方法

于 2012-04-03T05:00:53.297 回答
1

您拥有的代码应该可以工作,除非您有太多演员表

TextBox myText = FindControl["mycontrol"] as TextBox;

FindControl上的 MSDN 文档返回 a Control,它是Textbox的基类,因此只要找到的控件是文本框,此转换就应该起作用

于 2012-04-03T04:51:45.597 回答