此代码中发生的事情是DRV变量为null,而ListView中的项目计数为3。有人可以告诉我我做错了什么吗?
private void btn_save_Click(object sender, RoutedEventArgs e)
{
DataRowView drv;
bool valueToCheck;
List<Common.Rule> lst = new List<Common.Rule>();
Common.Rule ru = new Common.Rule();
lst = rr.GetAllRules().ToList();//getting all rules from database
for (int i = 0; i < ltv_rules.Items.Count; i++)
{
drv = ltv_rules.Items.GetItemAt(i) as DataRowView;
valueToCheck = Convert.ToBoolean(drv["IsSet"]);// to get the value of the combobox isSet from the list view
ru = lst[i];//getting the value of the isSet before it was binded to the list view.
if (ru.IsSet != valueToCheck)//comparing the original value (before it was binded) to the value that i get from the listview
{
ru.IsSet = valueToCheck;
bool updated = rr.UpdateRule(ru);
}
}
}
您正在使用as
铸造。这对编译器说:"我不确定这个演员,所以如果它是无效的返回零的'。在某些情况下,这就是您想要的,但是在大多数情况下,您希望在无效的演员阵容中抛出一个例外。在后一种情况下,您使用(SomeType)myValue
铸造,因此,如果演员阵容无效,您将获得InvalidCastException
。
我很简单,您在行中表现出无效的演员:
drv = ltv_rules.Items.GetItemAt(i) as DataRowView;
我希望这会有所帮助。