C# LINQ: How to check object value of a listbox item and set color accordingly
I was wondering if this was possible. Here is the code that populates a listbox:
var allHolds =
from a in db.Record_HoldDatas
join f in db.LUT_Flavors on a.Flavor equals f.ID
into flavorNames
where开发者_如何学编程 a.HoldStatus == "Open"
from grouped in flavorNames
select new { a.HoldID, a.DateOpened, grouped.flavor, a.NonConformingItem,
Caption = a.HoldID + " - " + a.Package + " " + grouped.flavor };
lbxHoldCaption.DataSource = allHolds;
lbxHoldCaption.DisplayMember = "Caption";
what I want to do is write a loop that goes through each object in the listbox and uses a couple values to do some math. If the math result is a certain value, then I want it to change that item's background color.
I'm not sure how to use a foreach loop with this. Since the listbox is actually bound to a reference full of anonymous types
More specifically, this is what im doing: One of the values in the object returned from the query is datetime "DateOpened" I want to subtract todays datetime with that to determine the hours elapsed. i was using something like this
DateTime now = DateTime.Now;
DateTime then = //retrieved from query object
TimeSpan span = now - then;
I was hoping to do this whole thing with something like
foreach(Object obj in allHolds)
{
then = obj.DateOpened;
span = now - then;
if(span.TotalHours >= 48)
{
obj.BackColor = Color.Red;
}
}
but obviously this doesnt work because the referencing is all borked. Can someone help me out?
try this
var allHolds =
from a in db.Record_HoldDatas
join f in db.LUT_Flavors on a.Flavor equals f.ID
into flavorNames
where a.HoldStatus == "Open"
from grouped in flavorNames
select new { a.HoldID, a.DateOpened, grouped.flavor, a.NonConformingItem,
Caption = a.HoldID + " - " + a.Package + " " + grouped.flavor,
BackColor = (DateTime.Now - a.DateOpened).TotalHours >= 48 ? "Red" : "Blue" };
and
lbxHoldCaption.DataSource = allHolds;
lbxHoldCaption.DisplayMember = "Caption";
lbxHoldCaption.DataBindings.Add("BackColor", allHolds,"BackColor");
foreach (ListItem xx in ListBox1.Items)
{
if (Convert.ToInt32(xx.Value) == 3)
{
xx.Attributes["style"] = "background-color:red;";
}
}
dont forget about those properties of ListBox : DataTextField="Caption" DataValueField="DateOpened"
Simple, use the var keyword, that way you don't need to specify the type explicitly.
foreach(var obj in allHolds)
{
then = obj.DateOpened;
span = now - then;
if(span.TotalHours >= 48)
{
obj.BackColor = Color.Red;
}
}
精彩评论