Reputation: 356
I have a form which has 4 columns say Col1,Col2,Col2,Col4...
Each Column has a combo box (cmb1,cmb2,cmb3,cmb4) having values ranged from 1 to 3.
If I select value of cmb1 as 1, cmb2 as 2, cmb3 as 3, cmb4 as 2 .... I need to know which column had 1 as value,2 as value and 3 .
here the result should be like Col1 has 1 value , Col2 and Col4 has 2 value and Col3 has 3 value
Following is my code :
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");
}
This code is too lengthy .Which is the best way with minimum lines of code.
Upvotes: 1
Views: 63
Reputation: 5743
You can group by the value, then select the column name by Linq.
For display you can use 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
}
Upvotes: 2
Reputation: 424
ComboBox
has property named SelectedItem
, you can get the selectedvalue due to SelectedItem
.And set the Name
of Combox
.
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");
}
Upvotes: 2