问题描述
在我的Web应用程序中,我使用satalite程序集来本地化我的Web表单..
而不是将每个控件文本设置为resourcemanager getstring()
方法我尝试使用foreach循环
私有字符串rmg(字符串键)
{
返回resource.GetString(" key") ;
}
private Literal ctrl_txt()
{
foreach(Literal lit_xyz in this .Controls)
{
string str = lit_xyz.ID;
string key = str.Substring(3);
lit_xyz.Text = rmg(key);
返回lit_xyz;
}
返回null;
}
这个foreach genrate InvalidCastException ...我怎么能解决这个问题?
In my web application i use satalite assembly to localize my web form..
Instead of set the each control text to the resourcemanager getstring()
method i try to use foreach loop
private string rmg(string key)
{
return resource.GetString("key");
}
private Literal ctrl_txt()
{
foreach (Literal lit_xyz in this.Controls)
{
string str= lit_xyz.ID;
string key= str.Substring(3);
lit_xyz.Text= rmg(key);
return lit_xyz;
}
return null;
}
this foreach genrate InvalidCastException... How can i fix this??
推荐答案
你的foreach没有''' t表示仅使用
控件集合中的文字,它表示在控件中使用每个控件
,就像它是文字一样。
正如您所知,这不是真的。
Controls集合包含*可能*
为Literals的控件,因此:
foreach(控制ctrl in this.Controls)
{
Literal lit = ctrl as Literal;
if(lit!= null)
{
//使用Literal
}
//否则没有文字,请忽略它
}
注意:这个foreach只有一个级别,你找不到
孙子这条路。如果你想找到任何Literal,无论
有多深,你需要使用递归(如果这不是一个文字,
那么可能在控件的某个地方这个控件的集合
有一个Literal")
-
Hans Kesting
your foreach doesn''t mean "use only the Literals from
the Controls collection", it means "use every control
in Controls as if it were a Literal".
As you found out, that is not true.
The Controls collection consists of Controls that *might*
be Literals, so:
foreach (Control ctrl in this.Controls)
{
Literal lit = ctrl as Literal;
if (lit != null)
{
// work with the Literal
}
// else no literal, ignore it
}
Note: this foreach goes just one level deep, you don''t find
"grandchildren" this way. If you want to find any Literal, no matter
how deep, you need to use recursion ("if this is not a Literal,
then maybe somewhere in the Controls collection of this control
there is a Literal")
--
Hans Kesting
这篇关于使用foreach循环使用Literials !!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!