Reputation: 1300
In the coding below I am inserting items into a datagrid
from a combobox
.
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;
}
I've created a variable in my class below, where I want to be able to access the items in a different method and get the Sum total of my ItemSellingPrice.
My class:
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; }
}
Now my issue is that in the top method where I am inserting the items into the datagrid, my displayItems
variable is always null for some reason. Is there some special way that I need to load the items into the displayItems
list in my class?
Upvotes: 0
Views: 83
Reputation: 4978
You don't need to store the whole collection of selected items on each item you add to the DataGrid. You can retrieve the collection from the DataGrid itself, and you can do so using a calculated property like this, for instance (you may need to add System.Linq
to your usings):
private IEnumerable<ExtraDisplayItems> SelectedDisplayItems
{
get
{
return dgAddExtras.Items.Cast<ExtraDisplayItems>();
}
}
That way, you can remove the list from the ExtraDisplayItems
class.
public class ExtraDisplayItems
{
public int ItemId { get; set; }
public string ItemCode { get; set; }
public string ItemDescription { get; set; }
public double? ItemSellingPrice { get; set; }
}
Your SelectionChanged
method would end up like this:
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;
}
And in your other method that needs to calculate the sum of ItemSellingPrice
, you just need to use the calculated property.
private void YourOtherMethod()
{
// do stuff
var sum = SelectedDisplayItems.Sum(item => item.ItemSellingPrice ?? 0); // Since ItemSellingPrice can be null, use 0 instead
// do more stuff
}
Upvotes: 2
Reputation: 10744
cmbAddExtras.SelectedItem
is not of type ExtraDisplayItems
. It is either null or a different type
Upvotes: 0