2015-10-05 41 views
0

我希望如果第2行中的任何文本框與第2行中的任何其他文本框具有相同的文本,它們都會獲得紅色的背景色。這是我迄今爲止所做的:等於任何其他文本框的文本框

private void Form1_Load(object sender, EventArgs e) 
{ 
    foreach (Control c in this.Controls) 
    { 
     if (c is TextBox && c.Name.StartsWith("textBox2")) 
     { 
      ((TextBox)c).TextChanged += textBox_TC; 
     } 
    } 
} 

private void textBox_TC(object sender, EventArgs e) 
{    
    TextBox textBox = (TextBox)sender;   
    if(textBox.Text == textBox.Text && textBox.Text.Length == 1) 
    { 
     textBox.BackColor = System.Drawing.Color.Red; 
    } 
    if (textBox.Text.Length == 0) 
    { 
     textBox.BackColor = System.Drawing.Color.White; 
    } 
} 

而不是如果textBox.Text == textBox.Text。我希望它是像textBox.Text == anyother.textBox.Text與名稱以textBox2開頭的東西。 這是可能的還是我不得不採取其他方式呢?

+0

你有多少這些'textBox2's? – PoweredByOrange

+0

9,我正在做一個sudoku – Percutient

回答

1

開始建立與具有同一起跑線名

List<TextBox> box2; 

private void Form1_Load(object sender, EventArgs e) 
{ 
    // Using LINQ to extract all the controls of type TextBox 
    // having a name starting with the characters textBox2 
    // BE AWARE - Is case sensitive - 
    box2 = this.Controls.OfType<TextBox>() 
         .Where(x => x.Name.StartsWith("textBox2")).ToList(); 

    // Set to each textbox in the list the event handler 
    foreach(TextBox t in box2) 
     t.TextChanged += textBox_TC; 

} 
在TextChanged事件

現在文本框一個List<TextBox>你可以寫

private void textBox_TC(object sender, EventArgs e) 
{    
    TextBox textBox = (TextBox)sender; 
    if(textBox.Text.Length == 1) 
    { 
     // Check if Any text box has the same text has the one 
     // firing the event (excluding the firing textbox itself) 
     bool sameText = box2.Any(x => x.Text == textBox.Text && 
            !x.Equals(textBox)); 

     // Got one textbox with the same text? 
     if(sameText) 
      textBox.BackColor = System.Drawing.Color.Red; 
    } 
    else if (textBox.Text.Length == 0) 
    { 
     textBox.BackColor = System.Drawing.Color.White; 
    } 
} 

編輯
根據您在下面的評論,你可以確保以這種方式重新設置背景顏色

警告未測試:只需追蹤一下。

private void textBox_TC(object sender, EventArgs e) 
{    
    TextBox textBox = (TextBox)sender; 
    if(textBox.Text.Length == 1) 
    { 
     foreach(TextBox t in box2) 
      t.BackColor = Color.White; 

     // Get all textboxes with the same text 
     var sameText = box2.Where(x => x.Text == textBox.Text); 
     if(sameText.Count() > 1) 
     { 
      foreach(TextBox t in sameText) 
       t.BackColor = Color.Red; 
     } 
    } 
    else if (textBox.Text.Length == 0) 
    { 
     textBox.BackColor = System.Drawing.Color.White; 
    } 
} 
+0

我複製了你的代碼,我在這裏得到一個錯誤「x.Name.StartsWith(」textbox2「)。ToList();」。應該在「.Where」前面有什麼?我以前沒有看過這個代碼。 – Percutient

+0

我在第一稿中忘記了一個括號 – Steve

+0

增加了一些註釋來解釋代碼。 – Steve

相關問題