【发布时间】:2022-01-04 19:02:51
【问题描述】:
我正在使用 C# 使用 winforms,我想检查我的一个文本框是否与我的文本框数组中的任何其他文本框具有相同的值。用户在文本框中输入值,如果输入任何重复值,则会显示错误。当我使用带有 for 循环的 textchanged 事件处理程序来遍历整个数组时,它会检查每个文本框,而不是将仅更改文本的文本框与其他文本框进行比较。
public partial class Form1 : Form
{
TextBox[,] textBoxArray = new TextBox[5, 5];
public Form1()
{
InitializeComponent();
textBoxArray[0, 0] = textBox1;
textBoxArray[0, 1] = textBox2;
textBoxArray[0, 2] = textBox3;
textBoxArray[0, 3] = textBox4;
textBoxArray[0, 4] = textBox5;
textBoxArray[1, 0] = textBox6;
textBoxArray[1, 1] = textBox7;
textBoxArray[1, 2] = textBox8;
textBoxArray[1, 3] = textBox9;
textBoxArray[1, 4] = textBox10;
textBoxArray[2, 0] = textBox11;
textBoxArray[2, 1] = textBox12;
textBoxArray[2, 2] = textBox13;
textBoxArray[2, 3] = textBox14;
textBoxArray[2, 4] = textBox15;
textBoxArray[3, 0] = textBox16;
textBoxArray[3, 1] = textBox17;
textBoxArray[3, 2] = textBox18;
textBoxArray[3, 3] = textBox19;
textBoxArray[3, 4] = textBox20;
textBoxArray[4, 0] = textBox21;
textBoxArray[4, 1] = textBox22;
textBoxArray[4, 2] = textBox23;
textBoxArray[4, 3] = textBox24;
textBoxArray[4, 4] = textBox25;
}
private void newGame_Click(object sender, EventArgs e)
{
Random rand = new Random();
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
textBoxArray[i, j].Text = "";
textBoxArray[i, j].ReadOnly = false;
}
}
int randomNum = rand.Next(0, 5);
textBoxArray[randomNum, randomNum].Text = "1";
}
private void ifTextChanged (object sender, EventArgs e)
{
// Set textbox with Value 1 to Read Only
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (textBoxArray[i, j].Text.Equals("1"))
{
textBoxArray[i, j].ReadOnly = true;
}
}
}
}
【问题讨论】:
-
这在
TextChanged()事件中不是一个好主意,因为用户可能没有完成输入他们的值,但您已经将 TextBox 设为只读,即使下一次击键可能会改变事物的状态.事实上,您没有任何代码可以关闭之前打开的只读状态。如果您过早地将它们锁定,它们将如何继续输入击键?... -
@Idle_Mind 我有一个新的游戏方法可以重置所有内容,我想先解决重复问题,然后返回并使用 1 整数解决该问题
-
我不确定我是否理解问题,但 TextChanged 事件中的
object sender是已更改的 TextBox。您可以简单地将发件人转换为 TextBox。