2013-10-15 127 views
0

我需要在表中顯示一些數據,但是我沒有在緊湊框架中使用類/對象。 該表不必做任何事情,只是顯示數據。 我有數據網格試過這樣:在緊湊的框架中創建一個表

DataGrid table = new DataGrid(); 
table.Location = new Point(13,190); 
table.Size = new Size(221,100); 
List<int> list = new List<int>(); 
list.Add(5); 
list.Add(7); 
list.Add(9); 
table.DataSource = list; 
this.Controls.Add(table); 

但這產生什麼似乎是一個空的DataGrid(一列,四行一排有一個箭頭)。

回答

1

你的原因「空」網格是:

To bind the DataGrid to a strongly typed array of objects, the object type must contain public properties

您使用int爲列表類型的參數,但int沒有性的判定來顯示。 用其他類型的公共屬性替換列表類型參數,並得到你想要的。

這裏,試試這個:

DataGrid table = new DataGrid(); 
    table.Location = new Point(0, 0); 
    table.Size = new Size(221, 100); 
    List<KeyValuePair<object, object>> list = new List<KeyValuePair<object, object>>(); 
    list.Add(new KeyValuePair<object, object>("asdfasdf", 3685745)); 
    list.Add(new KeyValuePair<object, object>("sdfgsdfgsd", 54)); 
    list.Add(new KeyValuePair<object, object>("xcvbxcvbxcvb", 341234)); 
    list.Add(new KeyValuePair<object, object>("56785678567", 56)); 
    table.DataSource = list; 
    this.Controls.Add(table); 

如果你需要顯示像整數或字符串數​​據,你可以使用LINQ做到這一點:

table.DataSource = list.Select(item=>new {item}).ToList(); 
+0

好的,但是我想要得到空的datagrid,即使這樣做? 'public struct Data { public string val1; public string val2; } DataGrid table = new DataGrid(); table.Location = new Point(13,190); table.Size = new Size(221,100); List list = new List (); Data stuff = new Data(); stuff.val1 =「3」; stuff.val2 =「A」; list.Add(stuff); table.DataSource = list; this.Controls.Add(table);' – Jonny

+0

沒關係,錯過了getter和setter,對不起。 謝謝先生 – Jonny

0

相反的List<int>,請嘗試使用列表對象,其中對象是您寫入來存儲數據的類。

下面是一個例子:

public class MyData { 

    public MyData() { 
    Date = DateTime.MinValue; 
    } 

    public int ID { get; set; } 

    public string Text { get; set; } 

    public DateTime Date { get; set; } 

    public override ToString() { 
    return string.Format("{0}: {1}", ID, Text); 
    } 

} 

現在,使用MyData類來創建你的列表,並與......凡是你必須填寫:

var list = new List<MyData>(); 
list.Add(new MyData() { ID = 5, Text = "5", new DateTime(2012, 5, 1) }); 
list.Add(new MyData() { ID = 7, Text = "7", new DateTime(2012, 7, 1) }); 
list.Add(new MyData() { ID = 9, Text = "9", new DateTime(2012, 9, 1) }); 
table.DataSource = list; 

而且,供參考:字table對於DataGrid實例不是一個好選擇。這裏的人不會知道你在說什麼。