C# 对aspx中的现有文本进行对象引用
如何对我在aspx页面中声明的文本进行对象引用。 现在我将它用作C# 对aspx中的现有文本进行对象引用,c#,asp.net,object-reference,C#,Asp.net,Object Reference,如何对我在aspx页面中声明的文本进行对象引用。 现在我将它用作ltlContents.Text=……,但我需要引用该ltlContents,这样我就可以在静态方法中使用它,就像使用它的.Text属性一样 我尝试了类似Literal ltl=…的方法,但这对我来说是新的,因为它不同于通常的对象引用,因为它来自前端 更新:我想在如下静态方法中使用ltlContents对象:ltlContents.Text=valueFromSomeFunction,但编译器给了我以下错误:非静态字段、方法需要对象
ltlContents.Text=……
,但我需要引用该ltlContents
,这样我就可以在静态方法中使用它,就像使用它的.Text
属性一样
我尝试了类似Literal ltl=…
的方法,但这对我来说是新的,因为它不同于通常的对象引用,因为它来自前端
更新:我想在如下静态方法中使用ltlContents对象:
ltlContents.Text=valueFromSomeFunction
,但编译器给了我以下错误:非静态字段、方法需要对象引用,或属性\u Default.ltlContents
您需要对控件或该控件所在页面的引用。此页必须在实际的生命周期中运行。例如,从webmethod中,您无法访问控件
但是,您甚至可以从静态方法访问此控件,这似乎是您想要的:
public static void SetControlText(string controlID, string text)
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
Control ctrl = FindControlRecursive(page, controlID);
if(ctrl != null)
{
ITextControl txt = ctrl as ITextControl;
if(txt != null)
txt.Text = text;
}
}
}
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id) return root;
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null) return t;
}
return null;
}
现在,在页面的生命周期中,这一点随处可见:
SetControlText("ltlContents", "Hello world");
因为对于每个请求,都会提供一个新的页面对象作为响应(它们的html)。 因此不可能做到这一点。
不要对函数使用
literal
,而是让函数从函数返回一个值并使用它。或者使用literal的值来运行。ltlContents
已经是代码隐藏中的对象。你具体看到了什么问题?@AdrianWragg-我更新了我的帖子。