检查文本框是否与其他文本框具有相同的值

时间:2014-11-28 13:19:27

标签: c# asp.net validation

我想检查一下我的文本框中是否有类似的值,我有10个文本框,按下按钮我想验证是否有相同的值

for (int c = 1; c <= 10; c++)
{
    TextBox check_subjName = table_textboxes.FindControl("subject_name" + c.ToString()) as TextBox;

    for (int b = 1; b <= 10; b++)
    {
        TextBox check_subjName2 = table_textboxes.FindControl("subject_name" + b.ToString()) as TextBox;

        if (c != b)
        {
            if (check_subjName.Text == check_subjName2.Text)
            {
              //there are similar values
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

因此,如果所有文本框都具有不同的值,则它是有效的。您可以使用LINQ:

List<string> textList = table_textboxes.Controls.OfType<TextBox>()
    .Where(txt => txt.ID.StartsWith("subject_name"))
    .Select(txt => txt.Text.Trim())
    .ToList();
var distinctTexts = new HashSet<string>(textList);
bool allDifferent = textList.Count == distinctTexts.Count;

这里是一种略微优化的方法(在这种情况下是微优化):

var textList = table_textboxes.Controls.OfType<TextBox>()
    .Where(txt => txt.ID.StartsWith("subject_name"))
    .Select(txt => txt.Text.Trim());
HashSet<string> set = new HashSet<string>();
bool allDifferent = textList.All(set.Add);