C# 是否可以从datagridview ColumnName中找到变量?

C# 是否可以从datagridview ColumnName中找到变量?,c#,winforms,variables,datagridview,C#,Winforms,Variables,Datagridview,我有个奇怪的问题。我有DataGridView,我有7列都是双精度的。我在包含信息的主类中有7个double数组 我如何制作这样的东西: if(dgvValues.Columns[dgvValues.SelectedCells[0].ColumnIndex].Name == this.Variables.Name) { this.Variables.Name[dgvValues.SelectedCells[0].RowIndex] = Convert.ToDouble(dgvVal

我有个奇怪的问题。我有
DataGridView
,我有7列都是双精度的。我在包含信息的主类中有7个double数组

我如何制作这样的东西:

if(dgvValues.Columns[dgvValues.SelectedCells[0].ColumnIndex].Name == this.Variables.Name)
{
       this.Variables.Name[dgvValues.SelectedCells[0].RowIndex] = Convert.ToDouble(dgvValues.SelectedCells[0].Value.ToString());
}

我知道我可以用case来做,但我想知道有没有一条捷径可以做到这一点。因为如果我有20列,我就得写20个格。

把那些值放在
字典中

现在,您可以通过dgv列名访问每一个

// a named collection of lists of doubles:
Dictionary<string, List<double>> values = new Dictionary<string, List<double>>();

// set up the values-dictionary from column names:
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
    values.Add(column.Name, new List<double>());
}

// load all values into the values-dictionary from the dvg:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
        values[cell.OwningColumn.Name].Add( Convert.ToDouble(cell.Value) );
}

// after the List is filled (!) you can access it like an array:
// load selected values into the values-dictionary from the dvg:
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
    values[cell.OwningColumn.Name][cell.RowIndex] = Convert.ToDouble(cell.Value);
}

// reload selected values from the corresponding slots in the values-dictionary:
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
    cell.Value = values[cell.OwningColumn.Name][cell.RowIndex];
}
//双重列表的命名集合:
字典值=新字典();
//根据列名设置值字典:
foreach(dataGridView1.Columns中的DataGridViewColumn列)
{
Add(column.Name,new List());
}
//从dvg将所有值加载到值字典:
foreach(dataGridView1.Rows中的DataGridViewRow行)
{
foreach(row.Cells中的DataGridViewCell单元格)
值[cell.OwningColumn.Name].Add(Convert.ToDouble(cell.Value));
}
//填充列表(!)后,您可以像访问数组一样访问它:
//将所选值从dvg加载到值字典:
foreach(dataGridView1.SelectedCells中的DataGridViewCell单元格)
{
值[cell.OwningColumn.Name][cell.RowIndex]=Convert.ToDouble(cell.Value);
}
//从值字典中的相应插槽重新加载选定值:
foreach(dataGridView1.SelectedCells中的DataGridViewCell单元格)
{
cell.Value=值[cell.OwningColumn.Name][cell.RowIndex];
}

请注意,在使用数组索引器时,必须用所有行完全填充列表才能访问正确的插槽

我考虑过这种方法,但还有其他方法吗?总是有反射,但这可能是访问命名变量最有效的方法。你为什么不喜欢它?我没有说我不喜欢,只是想知道有没有更有效的方法。谢谢你的回答。:)谢谢字典和列表是有效的。