1

这是我的代码:

void Main() {
    List<Restaurant> restaurants = new List<Restaurant>();
}

class Restaurant {
    public int Id;
    public List<Complaint> Complaints = new List<Complaints>();
}

class Complaint {
    public string Name;
    public string Address;
    public int Age;
    public DateTime ComplaintDate;
}

我想在 DataGridView 控件中显示 RestaurantData 中包含的数据,它是 Restaurant 类的一个对象。首先,我想显示餐厅的 ID,然后是针对餐厅的投诉数量,使其看起来像这样(其中 ID 在 A 列,名称在 B 列,依此类推):

  • ID 姓名 地址 年龄 日期
  • 姓名 地址 年龄 日期
  • 姓名 地址 年龄 日期

我过去对 DataGridView 的使用仅限于 dataGridView1.DataSource = (some array)。但是,这次我要呈现的信息显然不是数组,所以我被卡住了。

4

1 回答 1

1

如果您想将列剔除到您自己的列表中,可以使用以下方法:

private void AddColumns()
{
    dataGridView1.AutoGenerateColumns = false;
    DataGridViewTextBoxColumn ageColumn =
        new DataGridViewTextBoxColumn();
    ageColumn.Name = "Age";
    ageColumn.DataPropertyName = "Age";
    ageColumn.ReadOnly = true;

    DataGridViewTextBoxColumn nameColumn =
        new DataGridViewTextBoxColumn();
    nameColumn.Name = "Name";
    nameColumn.DataPropertyName = "Name";
    nameColumn.ReadOnly = true;

    DataGridViewTextBoxColumn addressColumn =
        new DataGridViewTextBoxColumn();
    addressColumn.Name = "Address";
    addressColumn.DataPropertyName = "Address";
    addressColumn.ReadOnly = true;

    DataGridViewTextBoxColumn dateColumn =
        new DataGridViewTextBoxColumn();
    addressColumn.Name = "Date";
    addressColumn.DataPropertyName = "Date";
    addressColumn.ReadOnly = true;

    dataGridView1.Columns.Add(ageColumn);
    dataGridView1.Columns.Add(nameColumn);
    dataGridView1.Columns.Add(addressColumn);
    dataGridView1.Columns.Add(dateColumn);

    var ds = (from r in restaurants
              from c in r.Complaints
              select new {Id = r.Id, Address =c.Address, Age = c.Age, Name = c.Name, Date = c.ComplaintDate}
             ).ToList();
    dataGridView1.DataSource = ds;
}

如果您只想自动生成列,请尝试以下操作:

private void AddColumns()
{
    dataGridView1.AutoGenerateColumns = true;

    var ds = (from r in restaurants
              from c in r.Complaints
              select new {Id = r.Id, Address =c.Address, Age = c.Age, Name = c.Name, Date = c.ComplaintDate}
             ).ToList();
    dataGridView1.DataSource = ds;
}
于 2013-09-27T20:52:21.817 回答