首页 > 解决方案 > 如何在 C# 中的多列 ListView 中导入学生列表?

问题描述

我想将 Student、DOB、Location 的列表导入 ListView1

我的代码导致“Nil”值,一直试图修复几个小时但没有运气

任何帮助是极大的赞赏。

        List<Student> students = new List<Student>() {
            new Student() { name = "AAA", dob = DateTime.ParseExact("10-05-2000", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Mumbai"},
            new Student() { name = "BBB", dob = DateTime.ParseExact("05-02-2000", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Pune"},
            new Student() { name = "CCC", dob = DateTime.ParseExact("01-01-2000", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Delhi"},
            new Student() { name = "DDD", dob = DateTime.ParseExact("20-03-1999", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Lucknow"},
            new Student() { name = "EEE", dob = DateTime.ParseExact("15-06-1999", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Chennai"},
            new Student() { name = "FFF", dob = DateTime.ParseExact("18-09-1999", "dd-MM-yyyy", CultureInfo.InvariantCulture), location = "Ahmedabad"}
        };


        var results = students.OrderByDescending(x => x.dob)  //sort from youngest to oldest
            .GroupBy(x => x.dob.Year) //group by year
            .Select(x => x.First())  //get first student born each year which is youngest
            .ToList();

        listView1.Items.Clear();
        int counterOfArraylist = results.Count;
        string[] str = new string[counterOfArraylist];
        for (int i = 0; i < str.Length; i++) { str[i] = results[i].ToString(); }
        listView1.Items.Add(new ListViewItem(str)); 

    }
}

public class Student
{
    public DateTime dob { get; set; }
    public string name { get; set; }
    public string location { get; set; }
}

标签: c#listview

解决方案


为了results[i].ToString();按预期工作,您应该重写ToString()类的方法并返回您喜欢的值:

public class Student
{
    public DateTime dob { get; set; }
    public string name { get; set; }
    public string location { get; set; }

    public override string ToString()
    {
        return name + " - " + dob.ToString("MMM dd, yyyy")+ " - " +location;
    }
}

或者只是将其内联添加到您的代码中:

 for (int i = 0; i < str.Length; i++) { str[i] = return name + " - " + dob.ToString("MMM dd, yyyy")+ " - " +location; }

如果您希望将每个属性放在单独的列中,那么您可以简单地执行以下操作:

ListViewItem[] items = results
   .Select(x => new ListViewItem(new string[]{x.name, x.dob.ToString("MMM dd, yyyy"), x.location})
    .ToArray();

listView1.Items.AddRange(items);

推荐阅读