【发布时间】:2017-03-20 04:44:10
【问题描述】:
我会尽量让你知道我想要做什么。
假设我的 datagridview/table 中有 4 列:
+----+-------------+------------+------------+ |身份证 |说明 |类型 |班级 | +----+-------------+------------+------------+ | 1 |软 |草莓 |水果 | | 2 |圆形 |葡萄 |水果 | | 3 |夏普 |铅笔 |文具 | +----+-------------+------------+------------+这是程序完成后的最终形式。
假设第二行和最后一行是空的,第三行 Type 是唯一可用的。
我最初尝试使用这样的开关代码块进行类似的操作:
switch (Type)
{
(Strawberry){
B2 = Soft;
C3 = Fruit;
}
(Grape){
etc...
}
}
基本上,我们将类型作为其他两个单元格的标准参数。 草莓软有果味,葡萄圆润有果味等。
我被建议使用字典而不是 switch 块,因为标准很长(可能有 1000 种类型),但是据我所知,虽然可以使用键(如草莓或葡萄)调用字典,但它会只能返回一种类型,比如 Description 的数据。此外,与使用 switch 语句编写字典相比,我不知道如何将字典写入 datagridview 格式。
我为未来的观众提出的解决方案:
public class DictionarySetup
{
public string theDescription { get; set; }
public string theClass { get; set; }
}
public class DictionaryInit
{
public Dictionary<int, DictionarySetup> accountRevenue = new Dictionary<int, DictionarySetup>()
{
{ 400000, new DictionarySetup {theDescription="Black", theClass="Weapon"}},
{ 400001, new DictionarySetup {theDescription="White", theClass="Mouse"}},
{ 410000, new DictionarySetup {theDescription="Opaque", theClass="Obstacle"}}
};
}
主动控制:
DictionaryInit theDictionary;
private void btnFixer_Click(object sender, EventArgs e)
{
theDictionary = new DictionaryInit();
for (int rowindex = 0; rowindex < DGVMain.RowCount; rowindex++)
{
foreach (var item in theDictionary.accountRevenue)
{
int theKey = item.Key;
DictionarySetup theValues = item.Value;
DGVMain.Rows[rowindex].Cells[5].Value = theValues.theDescription;
DGVMain.Rows[rowindex].Cells[6].Value = theValues.theClass;
}
}
}
【问题讨论】:
标签: c# arrays dictionary datagridview switch-statement