C# 无法从窗体上的文本框中获取值
因此,我试图从文本框中获取用户输入,这些文本框通过循环和if语句打印到屏幕上。当试图打印放入文本框的值时,我只得到一个值。以下是将文本框添加到网格的代码:C# 无法从窗体上的文本框中获取值,c#,winforms,C#,Winforms,因此,我试图从文本框中获取用户输入,这些文本框通过循环和if语句打印到屏幕上。当试图打印放入文本框的值时,我只得到一个值。以下是将文本框添加到网格的代码: private void InsertEasyNums() { int x = 70; int y = 40; for (int i = 0; i < 9; i++) { if (i == 3) {
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;
}
}
}
答:我将userInput的声明移动到方法的开头,循环9次,得到9个文本框,然后使用if语句移动它们并更改属性。尝试在循环之前移动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);
}
尝试在循环之前移动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);
}
解释你的程序在使用时应该做什么。想想数独。基本上,有些数字用户无法更改,而有些空框供用户键入数字。我只是在从用户应该使用的文本框中获取值时遇到了问题。好的,下面是一个关于如何在WinForms中编写数独的非常好的示例:现在你想实现什么,因为显然你没有使用数字?你在寻找同样的网格布局,并在苦苦挣扎到底是什么?解释你的程序在使用它时应该做什么。想想数独。基本上,有些数字用户无法更改,而有些空框供用户键入数字。我只是在从用户应该使用的文本框中获取值时遇到了问题。好的,下面是一个关于如何在WinForms中编写数独的非常好的示例:现在你想实现什么,因为显然你没有使用数字?您正在寻找相同的网格布局,并与到底是什么进行斗争?不起作用。当我尝试使用普通的foreach循环打印时,我得到userInput[I]=null;我假设这意味着,当声明userInput的循环仅通过,并且通常不会像1,2,3那样递增时,它更像是1,3,7,这会导致foreach上出现空值。当我尝试用空字符串手动填充数组时,仍然会出现相同的错误…不起作用。当我尝试使用普通的foreach循环打印时,我得到userInput[I]=null;我假设这意味着,当声明userInput的循环仅通过,并且通常不会像1,2,3那样递增时,它更像是1,3,7,这会导致foreach上出现空值。当我尝试用空字符串手动填充数组时,仍然会出现相同的错误。。。