我正在使用 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;
}
}
}
}
uj5u.com熱心網友回復:
將相同的文本更改事件處理程式放在所有文本框上:
private void Any_TextChanged(object sender, EventArgs e){
if(this.Controls.OfType<TextBox>().Any(tb => tb != sender && tb.Text == (sender as TextBox).Text))
MessageBox.Show((sender as TextBox).Text = "Dupe";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/372224.html
