动态数值的开关箱

本文关键字:开关箱 动态 | 更新日期: 2023-09-27 18:15:54

这是我的Program

你可以添加尽可能多的行,你想要这个网格视图,当你按下"准备"按钮,程序通过KeyDown-Event观察你的输入。当你按下网格视图中显示的热键之一时,你会得到匹配路径中的所有歌曲。

我想我可以这样做:

switch (e.KeyValue.ToString().Substring(0, 0))    
{
    foreach (DataGridViewRow  item in grdView)
    {
        case item.Cells[2].Value:
        //Get all the songs
        break;
    }        
}

不幸的是我得到了大量的错误。我想这样行不通。有没有其他的方法来要求所有热键写在gridview?

谢谢你的建议

动态数值的开关箱

foreach (DataGridViewRow item in grdView)
{
    if(item.Cells[2].Value == theValueYouAreLookingFor)
    {
        // Do something here
        break;
    }
}

还有e.p keyvalue。tostring()。Substring(0,0)看起来不太对,我很确定它不会做你想要它做的事情

虽然使用foreach遍历所有条目并检查是否相等可以工作,

我认为有必要提一下其他的选择,以防将来有人发现:

一个是Linq:

var itemFound = grdView.FirstOrDefault(item => item.Cells[2].Value == theValueYouAreLookingFor);
if (itemFound == null)
{
    //no items found in this case
}

另一个是Dictionary,它通常是映射动态选项的更有效的解决方案,但如果您必须事先构建它:

简单构建示例(在创建/更改网格时执行):

shortcutsMap = grdView.ToDictionary(item => item.Cells[2].Value, item);

得到:

var itemFound = shortcutsMap[theValueYouAreLookingFor] //will throw exception if not found

或:

shortcutsMap.TryGetValue(theValueYouAreLookingFor, out var itemFound) //returns true/false if found and result will be at itemFound