2013-09-27 45 views
1

這是我的代碼:如何在C#中的DataGridView中顯示我的對象的內容?

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; 
} 

希望呈現包含在RestaurantData,類餐廳的一個對象中的數據,在DataGridView控制I。首先,我想顯示餐廳ID,然後顯示餐廳的投訴數量,以便看起來像這樣(ID在A列,名稱在B列等):

  • ID名稱地址年齡日期
  • 姓名地址年齡日期
  • 姓名地址年齡日期

我的DataGridView的過去的使用已不限於dataGridView1.DataSource =(一些陣列)。但是,這次我想呈現的信息顯然不是數組,所以我被卡住了。

+0

你在找什麼東西像[這](http://stackoverflow.com/q/18926575/643085)? –

+0

我認爲這是WinForms,因爲你以前的問題是Winforms正確的? – paqogomez

+0

該答案應該有。對不起,我花了一些時間,中間回答。 – paqogomez

回答

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; 
} 
+0

這是如何解決OP正在討論的Master-Detail(嵌套網格)問題的? –

+0

@HighCore我正在努力,當我被拉走。更新的答案應該有它。 – paqogomez

+0

我不確定那是OP想要的。我想我們必須要求澄清。順便說一下,[this](http://www.devexpress.com/Subscriptions/DXperience/WhatsNew2012v1/i/xpf-grid-master-detail-table-views.png)就是我說的「主/細節」 –

相關問題