0

这段代码中发生的情况是,当列表视图中的项目数为 3 时,drv 变量为空。谁能告诉我我做错了什么吗?

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);
        }
    }
}
4

1 回答 1

0

您正在使用as. 这对编译器说,'我不确定这个转换,所以如果它无效,则返回 null'。在某些情况下,这是您想要的,但在大多数情况下,您希望在无效转换时抛出异常。在后一种情况下,您使用 进行转换(SomeType)myValue,因此如果转换无效,您将获得InvalidCastException.

我简而言之,您正在在线执行无效转换:

drv = ltv_rules.Items.GetItemAt(i) as DataRowView;

我希望这有帮助。

于 2014-02-05T16:26:20.010 回答