如何重构以编程方式构建某些 DataGridViews 列?

How to refactor the programmatically building of some DataGridViews columns?

我正在尝试构建一些数据网格视图。我目前正在使用下面显示的代码。我想知道是否有更有效的方法来构建列。我试过这个方法 ,但似乎无法正常工作。有人有什么建议吗?

        DataGridView hire = form1.hireDataGridView;
        hire.ColumnCount = 6;
        hire.Columns[0].Name = "Name";
        hire.Columns[1].Name = "Type";
        hire.Columns[2].Name = "Date";
        hire.Columns[3].Name = "Cost";
        hire.Columns[4].Name = "Start Date";
        hire.Columns[5].Name = "End Date";

        DataGridView service = form1.serviceDataGridView;
        service.ColumnCount = 5;
        service.Columns[0].Name = "Name";
        service.Columns[1].Name = "Type";
        service.Columns[2].Name = "Date";
        service.Columns[3].Name = "Cost";
        service.Columns[4].Name = "Description";

        DataGridView relocate = form1.relocationDataGridView;
        relocate.ColumnCount = 9;
        relocate.Columns[0].Name = "Name";
        relocate.Columns[1].Name = "Type";
        relocate.Columns[2].Name = "Date";
        relocate.Columns[3].Name = "Cost";
        relocate.Columns[4].Name = "dist";
        relocate.Columns[5].Name = "latA";
        relocate.Columns[6].Name = "longA";
        relocate.Columns[7].Name = "latB";
        relocate.Columns[8].Name = "longB";

您可以创建一个包含每个网格列名称的字典:

using System.Collections.Generic;

private Dictionary<DataGridView, string[]> GridsSettings;

private void InitializeGridsSettings()
{
  if ( GridsSettings != null) return;
  GridsSettings = new Dictionary<DataGridView, string[]>
  {
    [hireDataGridView] = new string[]
    { "Name", "Type", "Date", "Cost", "Start Date", "End Date" },

    [serviceDataGridView] = new string[]
    { "Name", "Type", "Date", "Cost", "Description" },

    [relocationDataGridView] = new string[]
    { "Name", "Type", "Date", "Cost", "dist", "latA", "longA", "latB", "longB" },
  };
}

然后就可以动态生成:

  InitializeGridsSettings(); // Called from constructor for example

  foreach ( var grid in GridsSettings)
  {
    grid.Key.ColumnCount = grid.Value.Length;
    int indexColumn = 0;
    foreach ( string name in grid.Value )
      grid.Key.Columns[indexColumn++].Name = name;
  }

您还可以使用 table 每个网格的名称和类型:

GridsSettings = new Dictionary<DataGridView, List<(string, Type)>>
{
  [hireDataGridView] = new List<(string, Type)>
  { ("Name", typeof(string)) },

  [serviceDataGridView] = new List<(string, Type)>
  { ("Name", typeof(string)) },

  [relocationDataGridView] = new List<(string, Type)>
  { ("Name", typeof(string)) },
};

foreach ( var grid in GridsSettings)
{
  grid.Key.ColumnCount = grid.Value.Count;
  int indexColumn = 0;
  foreach ( var column in grid.Value )
  {
    grid.Key.Columns[indexColumn].Name = column.Item1;
    grid.Key.Columns[indexColumn].ValueType = column.Item2;
    indexColumn++;
  }
}

数据绑定也可以通过相同的方式设置数据库字段或对象属性名称,以及任何 suitable。