Pergunta

What is happening in this code is that the drv variable is being null while the count of items in the listview is 3. Can any one tell me what i'm doing wrong please?

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);
        }
    }
}
Foi útil?

Solução

You are casting using as. This says to the compiler, 'I am not sure about this cast so if it is invalid return a null'. In some cases this is what you want, but in most cases you want an exception to be thrown on invalid casts. In the latter case you cast using (SomeType)myValue, so that if the cast is not valid, you will get an InvalidCastException.

I short, you are performing an invalid cast on the line:

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

I hope this helps.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top