我有一个BindingList变量,我需要获取添加到其中的最后一项。下面的代码可以工作,但我想知道是否有更好的方法,或者我遗漏了什么:
WorkoutScheduleList[WorkoutScheduleList.IndexOf(WorkoutScheduleList[(WorkoutScheduleList.Count - 1)])].WorkoutScheduleID);它不是最容易读懂的,但它基本上是获取列表的计数并从中减去1,然后将其用于IndexOf方法,以获得添加到列表中的最后一项。
发布于 2012-06-06 22:49:28
您可以处理绑定列表的ListChanged事件,并保留添加的项的引用。
示例:
class Program
{
static object last_item;
static void Main(string[] args)
{
BindingList<object> WorkoutScheduleList = new BindingList<object>();
WorkoutScheduleList.ListChanged += (s, e) => {
if (e.ListChangedType == ListChangedType.ItemAdded)
last_item = WorkoutScheduleList[e.NewIndex];
};
WorkoutScheduleList.Add("Foo");
WorkoutScheduleList.Add("Bar");
WorkoutScheduleList.Insert(1, "FooBar");
//prints FooBar
Console.WriteLine(String.Format("last item added: {0}", last_item));
}
}https://stackoverflow.com/questions/10915474
复制相似问题