无法从表单上的文本框获取值

时间:2019-04-12 19:00:55

标签: c# winforms

因此,我试图从通过循环和if语句显示在屏幕上的文本框中获取用户输入。当尝试打印输入到文本框中的值时,我只能得到一个值。这是将文本框添加到网格的代码:

 private void InsertEasyNums()
    {
            int x = 70;
            int y = 40;

        for (int i = 0; i < 9; i++)
        {
            if (i == 3)
            {
                x = 70;
                y = 160;
            }
            else if(i == 6)
            {
                x = 65;
                y = 280;
            }
            if (easyNums[i] == '0')
            {
                DrawingField.SendToBack();
                int panelX = x + 300;
                int panelY = y + + 100;

                Font newFont = new Font("Arial", 25);
                Point tbLocation = new Point(panelX, panelY);
                userInput[i] = new TextBox();

                userInput[i].Name = "Row[i]TB";
                userInput[i].Font = newFont;
                userInput[i].Width = 50;
                userInput[i].Location = tbLocation;
                userInput[i].BorderStyle = BorderStyle.None;
                userInput[i].BackColor = DefaultBackColor;
                Controls.Add(userInput[i]);
                DrawingField.SendToBack();

                x = x + 145;
                DrawingField.SendToBack();
            }
            else if (easyNums[i] != '0')
            {
                DrawingField.SendToBack();
                Font drawFont = new Font("Arial", 30, FontStyle.Bold);
                Brush Numbers = new SolidBrush(Color.Black);
                Graphics g = DrawingField.CreateGraphics();
                g.DrawString(Convert.ToString(easyNums[i]), drawFont, 
                Numbers, x, y);
                x = x + 146;
            }

        }

    }

在这里我尝试打印文本框:

 foreach (Control c in DrawingField.Controls)
        {
            if (c is TextBox)
            {
                int i = 0;
                TextBox txt = (TextBox)c;
                string str = txt.Text;
                TBValues[i] = str;
                i++;


            }
        }
        foreach (var key in TBValues)
        {
            MessageBox.Show(key);
        }

答案:我将userInput的声明移到方法的开头,并循环9次以给出9个文本框,然后使用if语句移动它们并更改属性。

1 个答案:

答案 0 :(得分:0)

尝试在循环之前将i移动

       int i = 0;
 foreach (Control c in DrawingField.Controls)
    {
        if (c is TextBox)
        {

            TextBox txt = (TextBox)c;
            string str = txt.Text;
            TBValues[i] = str;
            i++;


        }
    }
    foreach (var key in TBValues)
    {
        MessageBox.Show(key);
    }