日期:2014-05-17  浏览次数:20822 次

求解惑!!遍历问题..
我要遍历窗体的textbox并判断值大小,如果大于100则背景色变红

C# code

foreach (Control col in this.Controls)
            {
                if (col is TextBox)
                {
                    int i = Convert.ToInt32(col.Text);
                    if (i > 100)
                    {
                        col.BackColor = Color.Red;
                    }
                }

            }


代码第5行报错:"输入的字符串格式不对" 为什么?



------解决方案--------------------
应该是字符串中含有不能转换的字符,可以考虑使用int.tryparse
------解决方案--------------------
探讨
我要遍历窗体的textbox并判断值大小,如果大于100则背景色变红

C# code

foreach (Control col in this.Controls)
{
if (col is TextBox)
{
int i = Convert.ToInt32(c……

------解决方案--------------------
楼上正确。
------解决方案--------------------
C# code
Controls.OfType<TextBox>().Where(x => Regex.IsMatch(x.Text, @"\d+")).Where(x => int.Parse(x.Text) > 100).ToList().ForEach(x => x.BackColor = Color.Red);