是否有可能从datagridview ColumnName中找到变量?

时间:2014-09-15 10:18:54

标签: 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(dgvValues.SelectedCells[0].Value.ToString());
}

我知道我可以用案例来做,但我想知道是否有一个简短的方法。因为如果我有20列,我必须制作20个案例。

1 个答案:

答案 0 :(得分:1)

将这些值放在Dictionary<string, List<double>>中!

现在您可以通过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];
}

请注意,当您使用数组索引器时,您必须完全填充列表以使用所有行来访问正确的插槽!

相关问题