【问题标题】:Populate a datagridview with a list in the correct order使用正确顺序的列表填充 datagridview
【发布时间】:2019-07-21 14:27:51
【问题描述】:

基本上我有不同的列表:Employee、Cooker 和 Teacher。

当我想用其中一个填充我的 datagridview 时,它不会以正确的顺序显示对象的值。正确的顺序是什么意思?如果我的班级有id、name 和salary 属性或属性,我想以相同的顺序显示它们,而不是salary、name 和id。我应用了继承,所以我不知道这是否会导致一些问题。

我只是尝试用这个填充我的 datagridview。

dgvEmployess.DataSource = listOfCookers;

这是我的课程

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Employee : Person
{
    public double Salary { get; set; }
}

public class Teacher : Employee
{
    public int NumberOfStudents { get; set; }
}

public class Cooker : Employee
{
    public int ExtraHours { get; set; }
}

【问题讨论】:

    标签: c# list winforms datagridview


    【解决方案1】:

    如果您没有手动创建,默认情况下会自动创建列。

    dgvEmployess.AutoGenerateColumns = false; // Disable automated columns creation 
    dgvEmployess.DataSource = listOfCookers;
    

    按照需要的顺序手动创建列,并将DataPropertyName 设置为像薪水这样的属性名称

    【讨论】:

    • 谢谢先生。现在我可以完成我的项目了
    【解决方案2】:

    其中一种方法可能是创建一个自定义属性,该属性定义了类属性在显示中的顺序,以及一个读取自定义属性值并对列进行排序的函数:

    public class ColumnOrder : Attribute
    {
        public int Order { get; set; }
    }
    

    在类中,设置顺序(在本例中,顺序为 Id、Age、Salary、Name):

    public class Person
    {
        [ColumnOrder(Order = 1)]
        public int Id { get; set; }
        [ColumnOrder(Order = 25)]
        public string Name { get; set; }
        [ColumnOrder(Order = 3)]
        public int Age { get; set; }
    }
    
    public class Employee : Person
    {
        [ColumnOrder(Order = 10)]
        public double Salary { get; set; }
    }
    

    使用此扩展程序按其ColumnOrder 属性值对列进行排序。它迭代类型的属性,读取ColumOrder 的值并更改列的DisplayIndex

    public static class ColumnExtensions
    {
        public static void OrderByProperties(this DataGridViewColumnCollection columns,  Type t)
        {
            var columnList = new List<KeyValuePair<string, int>>();
            foreach (var prop in t.GetProperties())
            {
                var att = prop.GetCustomAttributes<ColumnOrder>( true).First();
                if(att!=null)
                {
                    columnList.Add(new KeyValuePair<string, int>(prop.Name,att.Order));
                }
            }
    
            foreach (var order in columnList.OrderBy(a => a.Value).Select((value, i) => new {i, value }))
            {
                columns[order.value.Key].DisplayIndex = order.i;
            }
        }
    }
    

    最后,绑定数据源后,使用正确的类型调用 OrderByProperties:

    dataGridView1.Columns.OrderByProperties(typeof(Employee));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 2017-11-19
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多