从listview获取价值

时间:2014-02-05 16:17:24

标签: wpf listview datarowview

此代码中发生的事情是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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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

我做空,你在线上进行了无效的演员阵容:

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

我希望这会有所帮助。