文本框等于任何其他文本框

时间:2015-10-05 17:37:11

标签: c# .net winforms

我想要它,以便如果我在第2行中的任何TextBox与第2行中的任何其他TextBox具有相同的文本,它们都会得到背景颜色为红色。这是我到目前为止所做的:

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开头。 这是可能的还是我必须以其他方式解决这个问题?

1 个答案:

答案 0 :(得分:1)

开始使用具有相同起始名称

的文本框构建List<TextBox>
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事件中编写

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;
    }
}