2011-06-16 33 views
0

我有一個名爲Result的類,它有4個字段id, marks, total, avg。我創建了List類並存儲了結果。在datagrid中顯示列表<t>的問題?

現在我想在數據網格中只顯示2列。他們是idtotal。我成功地顯示的ID和總,但數據網格顯示4列,而不是2列id, total, id, total

這裏是我的代碼顯示數據網格:

private void Form1_Load(object sender, EventArgs e) 
    { 
     List<Result> result = new List<Result>(); 
     PopulateResult(); 
     dgresult.AutoGenerateColumns = false; 
     dgresult.Items.Clear(); 
     dgresult.ItemsSource = result; 
     DataGridTextColumn col1 = new DataGridTextColumn(); 
     col1.Header = "Id"; 
     col1.Binding = new Binding("Id"); 
     DataGridTextColumn col2 = new DataGridTextColumn(); 
     col2.Header = "Total"; 
     col2.Binding = new Binding("Total"); 
     dgresult.Columns.Add(col1); 
     dgresult.Columns.Add(col2); 
    } 
} 
class Result 
{ 
    int id; 
    int total; 
    int marks; 
    int avg; 

    public int Id { get { return id; } set { id = value; } } 
    public int Total { get { return total; } set { total = value; } } 
    public int Marks { get { return marks; } set { marks = value; } } 
    public int Avg { get { return avg; } set { avg = value; } } 

    public Result(int ID, int TOTAL, int MARKS, int AVG) 
    { 
     id = ID; 
     total = TOTAL; 
     marks = MARKS; 
     avg = AVG; 
    } 
} 

我不明白爲什麼它正在發生喜歡這個。

在此先感謝。

+1

嘗試建立'Columns'之後設置'ItemsSource'。但是看不到如何調用'PopulateResult()'來填充你的'result'列表。 – 2011-06-16 15:54:04

+0

這是一個函數只是將結果添加到列表 – 2011-06-16 15:59:52

+0

沒有辦法,該函數調用填充結果。我猜想有些事情我不理解。 – 2011-06-16 16:46:15

回答

0

我添加註釋你的代碼,顯示我的想法:

private void Form1_Load(object sender, EventArgs e) 
{ 
    // Make a new list of result class objects, local to the Form1_Load method: 
    List<Result> result = new List<Result>(); 

    // Call a method that populates a list... wait, what list? 
    PopulateResult(); 

    dgresult.AutoGenerateColumns = false; 
    dgresult.Items.Clear(); 

    // Set the datagrid data source to the list created earlier 
    dgresult.ItemsSource = result; 
    // ... 

我不知道爲什麼DataGrid中有重複的組列您所指定並添加只有兩列後。這將有助於查看方法PopulateResult()

PopulateResult()正在添加的列表必須是其他列表,因爲Form1_Load中創建的列表在範圍上是局部的。

我不確定這只是一個小小的疏漏,或者您需要了解可變範圍。原諒我,如果這是已經知道你: