Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#for循环中的变量_C#_Variables - Fatal编程技术网

C#for循环中的变量

C#for循环中的变量,c#,variables,C#,Variables,我的申请表上有许多按钮。我想检查每个按钮的文本(比较)。我怎样才能做到 for (i = 1; i < 30; i++) { if (this.button1.Text == "Hello") //here is PROBLEM { //..some statement } } (i=1;i

我的申请表上有许多按钮。我想检查每个按钮的文本(比较)。我怎样才能做到

for (i = 1; i < 30; i++) 
{
   if (this.button1.Text == "Hello") //here is PROBLEM
   {
      //..some statement
   }   
}
(i=1;i<30;i++)的

{
如果(this.button1.Text==“Hello”)//这是个问题
{
//…一些声明
}   
}
所以下次这个.button1。文本必须更改为这个.button2。文本等等


此.button[i]。文本不工作。

按钮不是数组。每一个都是一个谨慎的对象,是其容器的子对象

理想情况下,您需要构建一个按钮集合(数组、列表等),并遍历该集合,而不是使用索引变量(i)


这里有一个很好的方法:

我很确定这是一个windows窗体。 在windows窗体中,您可以像这样迭代控件

foreach (Control c in panel.Controls)
{
    string cType = c.GetType().ToString();

    // check all buttons
    if (cType == "System.Web.UI.WebControls.Button")
    {
        if(((Button)c).Text == "Hello")
        {

        }
    }
}
因此,代码所做的是迭代面板中的所有控件,并检查每个控件的类型是否为按钮

更新: 正如韦斯利所说,更好的方法是像这样实现它

 if (c is Button && c.Text.Equals("Hello")) {
for(int i=1;i<3;i++)
{
var buttonName=“button”+i;
Button Button=this.Controls.Find(buttonName,true).FirstOrDefault()作为按钮;
字符串文本=按钮文本;
}

试试这段代码。

这是正确的语法:

foreach (Control button in this.Controls)
{
     if (button.GetType() == typeof(Button) && button.Text == "Hello")
     {
           //..some statement    
     }
}

这是Windows窗体、WPF、Windows应用程序吗?可能重复:您可以在Windows窗体中进行迭代,问题中说明这是一个应用程序form@Desperado-我没有断言这些都是假的。你使用了我的方法,获得了面板。控件集合并对其进行了迭代。很抱歉,我没有单击你的链接,你是对的,我们有相同的概念,我从我的旧代码中复制了我的答案推荐:if(c是Button&((Button)c)。Text.Equals(“Hello”){…}我很确定这是一个windows窗体与
System.Web.UI.WebControls
不匹配,抱歉@fubot这可能适用于给定的场景,但不推荐,因为它假设所有按钮都应命名为buttonX,这不是一个好的命名法。我知道。但是卡斯珀想做这种行为。他想找到一个固定名称的控件。这个代码语法帮助我解决了pazzle问题。谢谢。添加剧照让我了解了它的实际工作原理。
foreach (Control button in this.Controls)
{
     if (button.GetType() == typeof(Button) && button.Text == "Hello")
     {
           //..some statement    
     }
}