簡體   English   中英

檢索在C#中從中選擇值的列的名稱

[英]Retrieve the name of the column from which the values where chosen in C#

我有一個表格,其中有4列說Col1Col2Col2Col4 ...

每個列都有一個組合框( cmb1,cmb2,cmb3,cmb4 ),其值范圍為1到3。

如果我將cmb1的值選擇為1 ,將cmb2的值選擇為2 ,將cmb3的值選擇為3 ,將cmb4的值選擇2 ...。我需要知道哪一列的值是1,值是2,值是3。

這里的結果應該是Col1為1值Col2和Col4為2值Col3為3值

以下是我的代碼:

if (cmb1 == "1" && cmb2 == "1" && cmb3 == "1" && cmb4 == "1")
                {
                    Console.WriteLine("Col1,Col2,Col3,Col4");
                }
                if (cmb1 == "1" && cmb2 == "1" && cmb3 == "1")
                {
                    Console.WriteLine("Col1,Col2,Col3");
                }
                if (cmb1 == "2" && cmb2 == "2" )
                {
                    Console.WriteLine("Col1,Col2");
                }

這段代碼太長。用最少的代碼行是最好的方法。

ComboBox有一個名為屬性SelectedItem ,你可以得到的SelectedValue因SelectedItem 。而設定的NameCombox

  List<Combox> comboxs = new List<Combox>;
    comboxs.Add(cmb1);
    comboxs.Add(cmb2);
    comboxs.Add(cmb3);
    comboxs.Add(cmb4);
  foreach(var combox in comboxs){
    Console.WriteLine(combox.Name + "has" + combox.SelectedItem + "value");
  }

您可以按值分組,然后按Linq選擇列名稱。

為了顯示,您可以使用string.Join()

var cmb1 = "1";
var cmb2 = "2";
var cmb3 = "3";
var cmb4 = "2";

var selection = new Dictionary<string, string>() 
{ 
    {"Col1", cmb1},
    {"Col2", cmb2},
    {"Col3", cmb3},
    {"Col4", cmb4},
};

var result = selection
    .GroupBy(i => i.Value) // Group by your combo box values
    .Select(group =>
        new
        {
            Value = group.Key,
            Columns = group.Select(i => i.Key).ToArray()
        }
    );
foreach (var item in result) // for each value in your combo box
{
    Console.WriteLine(
        string.Format("Value: {0}, Columns: {1}",
        item.Value,
        string.Join(",", item.Columns)));

    string[] column = item.Columns; // It should store somewhere else, line for demo only
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM