如何解决如何重构一些 DataGridViews 列的编程构建?
我正在尝试构建一些数据网格视图。我目前正在使用下面显示的代码。我想知道是否有更有效的方法来构建列。我试过这个方法 post,但似乎无法让它工作。有人有什么建议吗?
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","Description" },[relocationDataGridView] = new string[]
{ "Name","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;
}
您也可以使用每个网格具有名称和类型的表格:
GridsSettings = new Dictionary<DataGridView,List<(string,Type)>>
{
[hireDataGridView] = new List<(string,Type)>
{ ("Name",typeof(string)) },[serviceDataGridView] = new List<(string,[relocationDataGridView] = new List<(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++;
}
}
数据绑定也可以用同样的方式来设置数据库字段或对象属性名称,以及任何合适的东西。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。