麻烦各位高手给看下下面的代码,那里出错了,遍历当前页面全部控件。窗体里面有groupBox以及panel
private void BcforLoading(Control container)
{
foreach (Control com in container.Controls)
{
if (com.HasChildren)
{
BcforLoading(com);
}
if (com.Name.Substring(com.Name.Length – 4, 4) == “_JCZ” && com is ComboBox)
{
ComboBox cb = (ComboBox)com;
cb.Items.Add(UserContext.LoggedUser);
cb.SelectedItem = UserContext.LoggedUser;
}
if (com.Name.Substring(com.Name.Length – 3, 3) == “_BZ” && com is ComboBox)
{
ComboBox cb = (ComboBox)com;
cb.SelectedValue = UserContext.LoggedUserTeam;
}
if (com.Name.Substring(com.Name.Length – 3, 3) == “_BC” && com is ComboBox)
{
ComboBox cb = (ComboBox)com;
cb.SelectedValue = UserContext.LoggedUserSort;
}
}
}
private void BcforLoading(Control container)
{
foreach (Control com in container.Controls)
{
if (com.HasChildren)
{
BcforLoading(com);
}
if (com.Name.Substring(com.Name.Length – 4, 4) == “_JCZ” && com is ComboBox)
{
ComboBox cb = (ComboBox)com;
cb.Items.Add(UserContext.LoggedUser);
cb.SelectedItem = UserContext.LoggedUser;
}
if (com.Name.Substring(com.Name.Length – 3, 3) == “_BZ” && com is ComboBox)
{
ComboBox cb = (ComboBox)com;
cb.SelectedValue = UserContext.LoggedUserTeam;
}
if (com.Name.Substring(com.Name.Length – 3, 3) == “_BC” && com is ComboBox)
{
ComboBox cb = (ComboBox)com;
cb.SelectedValue = UserContext.LoggedUserSort;
}
}
}
解决方案:10分
这错误应该是Substring(com.Name.Length – 4, 4),原因是假如com.Name的长度小于4,那么你执行的其实就是Substring(-1, 4),所以报错了,你要预先判断一下长度
解决方案:20分
吧条件表达式调一下位置
if (com.Name.Substring(com.Name.Length – 4, 4) == “_JCZ” && com is ComboBox)
改为
if (com is ComboBox && com.Name.Substring(com.Name.Length – 4, 4) == “_JCZ”)
if (com.Name.Substring(com.Name.Length – 4, 4) == “_JCZ” && com is ComboBox)
改为
if (com is ComboBox && com.Name.Substring(com.Name.Length – 4, 4) == “_JCZ”)