'Switch Case for dynamic amount of values
So this is my Program
You can add as much rows as you want to this gridview and when you press the 'Ready' button the program watches your input via the KeyDown-Event. When you press one of those Hotkeys shown in the gridview you get all the songs which are in the matching path.
I thought I could do something like this:
switch (e.KeyValue.ToString().Substring(0, 0))
{
foreach (DataGridViewRow item in grdView)
{
case item.Cells[2].Value:
//Get all the songs
break;
}
}
Unfortunatelly I get tons of errors. I guess it won't work like this. Is there any other way to ask for all Hotkeys written in the gridview?
Thanks for any kind of advice.
Solution 1:[1]
foreach (DataGridViewRow item in grdView)
{
if(item.Cells[2].Value == theValueYouAreLookingFor)
{
// Do something here
break;
}
}
And also e.KeyValue.ToString().Substring(0, 0) doesn't look right, I'm pretty sure that it isn't going to do quite what you want it to do.
Solution 2:[2]
Although iterating through all items with foreach and checking for equals would work,
I thought its worth to mention few alternative in case someone finds it in the future:
one is Linq:
var itemFound = grdView.FirstOrDefault(item => item.Cells[2].Value == theValueYouAreLookingFor);
if (itemFound == null)
{
//no items found in this case
}
the other is Dictionary which is a more efficient solution to map dynamic amount of options in general, but it you'll have to build it beforehand:
simple build example (do this when the grid is created/changed):
shortcutsMap = grdView.ToDictionary(item => item.Cells[2].Value, item);
get:
var itemFound = shortcutsMap[theValueYouAreLookingFor] //will throw exception if not found
or:
shortcutsMap.TryGetValue(theValueYouAreLookingFor, out var itemFound) //returns true/false if found and result will be at itemFound
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Robyn |
| Solution 2 | Rom Haviv |
