使用C#中的相同数据源防止多个组合框中的重复值

时间:2018-01-30 20:56:02

标签: c# if-statement combobox

我有五个组合框,都是从一个字符串字典中填充的,它存储来自datagridview的标题文本。 在我的节目中, 我想要一个消息框立即弹出选择重复值或按下确定按钮。  下面的代码是一个if语句,仅当其他组合框复制第一个组合框中的selectedvalue时才有效。

是否有比这长篇陈述更短的方式?我希望能够验证每个其他组合框,以便他们不会有重复。 P.S我希望弹出窗口继续出现,直到选择一个唯一值。 cbosort1,2,3..分别是组合框名称。

if (cboSort1.SelectedValue == cboSort2.SelectedValue || cboSort1.SelectedValue == cboSort3.SelectedValue || cboSort1.SelectedValue == cboSort4.SelectedValue || cboSort1.SelectedValue == cboSort5.SelectedValue)
{
  MessageBox.Show("you cannot choose a duplicate column", "duplicate error");
return;
}

2 个答案:

答案 0 :(得分:0)

var comboboxes = new[] { cboSort1, cboSort2, ...... };
bool dup = comboboxes.GroupBy(c => (string)c.SelectedValue).Any(g => g.Count() > 1);

OR

bool dup = comboboxes.GroupBy(c => (string)c.SelectedValue).Count() < comboboxes.Length;

答案 1 :(得分:0)

您可以先检测重复值,然后检查您的cb1-5是否为:

using System;
using System.Data;
using System.Linq;

namespace SO
{
    public class ComboBox { public string SelectedValue; }

    public class Program
    {
        public static void Main(string[] args)
        {
            var cboSort1 = new ComboBox { SelectedValue = "not a dupe" };
            var cboSort2 = new ComboBox { SelectedValue = "also not a dupe" };
            var cboSort3 = new ComboBox { SelectedValue = "this is a dupe" };
            var cboSort4 = new ComboBox { SelectedValue = "no dupe here" };
            var cboSort5 = new ComboBox { SelectedValue = "this is a dupe" };

            var boxes = new[] { cboSort1, cboSort2, cboSort3, cboSort4, cboSort5 };

            var dupes = boxes
                .GroupBy(cb => cb.SelectedValue)       # groups by the value
                .Where(grp => grp.ToList().Count > 1)  # this value has more then 1 
                .Select(grp => grp.Key);               # just select the SelectedValue

            // now you just check if your CB has this selectedValue:
            if (dupes.Any(d => d == cboSort1.SelectedValue))
                Console.WriteLine("CB1 is a dupe");
            if (dupes.Any(d => d == cboSort2.SelectedValue))
                Console.WriteLine("CB2 is a dupe");
            if (dupes.Any(d => d == cboSort3.SelectedValue))
                Console.WriteLine("CB3 is a dupe");
            if (dupes.Any(d => d == cboSort4.SelectedValue))
                Console.WriteLine("CB4 is a dupe");
            if (dupes.Any(d => d == cboSort5.SelectedValue))
                Console.WriteLine("CB5 is a dupe");        
        }
    }
}

输出:

CB3 is a dupe
CB5 is a dupe