2015-07-28 105 views
0

在下面的代碼中,我將項目從combobox插入到datagrid中。如何在列表中插入項目

private void cmbAddExtras_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    using (TruckServiceClient TSC = new TruckServiceClient()) 
    { 
     var item = cmbAddExtras.SelectedItem as ExtraDisplayItems; 

     if (item != null) 
     { 
      var displayItem = new List<ExtraDisplayItems> 
      { 
       new ExtraDisplayItems 
       {        
        ItemId = item.ItemId, 
        ItemCode = item.ItemCode, 
        ItemDescription = item.ItemDescription, 
        ItemSellingPrice = item.ItemSellingPrice, 
        displayItems = item.displayItems //Always null? 
       } 
      }; 
      dgAddExtras.Items.Add(item); 
     } 
    } 
    btnRemoveAllExtras.Visibility = Visibility.Visible; 
} 

我在下面我的課,在這裏我希望能夠訪問的項目在不同的方法,並得到總和總我ItemSellingPrice創建一個變量。

我的類:

public class ExtraDisplayItems 
{ 
    public List<ExtraDisplayItems> displayItems; 

    public int ItemId { get; set; }  
    public string ItemCode { get; set; }  
    public string ItemDescription { get; set; }  
    public double? ItemSellingPrice { get; set; } 
} 

現在我的問題是,在我插入的項目到DataGrid中的頂級方法,我displayItems變量始終是出於某種原因。是否有一些特殊的方法需要將這些項目加載到我班的displayItems列表中?

+0

你試過通過實例化displayItems嗎? – Karthik

+0

@湍流 - 感謝您的回覆! :)我怎麼去做這件事?請你給我舉個例子嗎? – CareTaker22

+0

Here you go 'public ExtraDisplayItems(){this.displayItems = new List ();}' – Karthik

回答

2

您不需要在添加到DataGrid的每個項目上存儲所選項目的整個集合。您可以檢索從DataGrid本身的集合,你可以這樣做,用計算出的屬性是這樣,例如(您可能需要添加System.Linq您usings):

private IEnumerable<ExtraDisplayItems> SelectedDisplayItems 
{ 
    get 
    { 
     return dgAddExtras.Items.Cast<ExtraDisplayItems>(); 
    } 
} 

這樣的話,你可以刪除列表從ExtraDisplayItems類。

public class ExtraDisplayItems 
{ 
    public int ItemId { get; set; }  
    public string ItemCode { get; set; }  
    public string ItemDescription { get; set; }  
    public double? ItemSellingPrice { get; set; } 
} 

SelectionChanged方法最終會是這樣的:

private void cmbAddExtras_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    // You're not using TSC, so you don't need this either 
    //using (TruckServiceClient TSC = new TruckServiceClient()) 
    //{ 
     var item = cmbAddExtras.SelectedItem as ExtraDisplayItems; 

     if (item != null) 
     { 
      dgAddExtras.Items.Add(item); 
     } 
    //} 
    btnRemoveAllExtras.Visibility = Visibility.Visible; 
} 

而且在需要計算的ItemSellingPrice總和的另一種方法,你只需要使用計算的屬性。

private void YourOtherMethod() 
{ 
    // do stuff 

    var sum = SelectedDisplayItems.Sum(item => item.ItemSellingPrice ?? 0); // Since ItemSellingPrice can be null, use 0 instead 

    // do more stuff 
} 
+0

哈哈哈woooow !!!我在這個問題上掙扎了很長時間,現在你給了我答案。它完美的工作!非常感謝你almulo! :D我不得不問的所有問題中的最佳答案。 – CareTaker22

+0

很高興我可以幫助:) – almulo

0

cmbAddExtras.SelectedItem不是ExtraDisplayItems類型。它是空的或不同的類型

+0

謝謝你的答案格倫,但這仍然給我的'displayItems'值** null **。 – CareTaker22

+0

然後你必須將它的值設置爲null。 –