开发者

Converting IQueryable to ObservableCollection, must know how

开发者 https://www.devze.com 2023-02-12 22:51 出处:网络
The question is why does the null reference occur for the observable collection? The error occurs when I try to add item to the obscollection.

The question is why does the null reference occur for the observable collection? The error occurs when I try to add item to the obscollection.

Note: I have to know how to give all items present in datagrid to observable collection.

Error:

Object reference not set to an instance of an object.

line:- "good.Add(temp_table);" in button one click

.xaml.cs

Web.DomainService1 oservice = new Web.DomainService1();
public static ObservableCollection<Web.EMP_TABLE> good = new ObservableCollection<Web.EMP_TABLE>();

public Home()
{
    InitializeComponent();
    this.Title = ApplicationStrings.HomePageTitle;

    EntityQuery<Web.EMP_TABLE> q = oservice.GetEMP_TABLE_OBVQuery();
    LoadOperation<Web.EMP_TABLE> l = oservice.Load(q);
    dataGrid1.ItemsSource = l.Entities;
}



private void button1_Click(object sender, System.Windows.Ro开发者_如何学JAVAutedEventArgs e)
{
    ObservableCollection<Web.EMP_TABLE> good = 
        dataGrid1.ItemsSource as ObservableCollection<Web.EMP_TABLE>;
    Web.EMP_TABLE temp_table = new Web.EMP_TABLE();
    temp_table.SALARY = "new_sal";
    temp_table.EMP_NAME = "new_name";
    temp_table.EMP_NO = "new_num";
    good.Add(temp_table);
}

.xaml

<sdk:DataGrid AutoGenerateColumns="True" Height="116" Name="dataGrid2" Width="539" />

The DomainService function

public ObservableCollection<EMP_TABLE> GetEMP_TABLE_OBV()
{
    var value = from c in this.ObjectContext.EMP_TABLE
                select c;
    ObservableCollection<EMP_TABLE> result = new ObservableCollection<EMP_TABLE>(value);
    return result;
}


ObservableCollection<Web.EMP_TABLE> good = dataGrid1.ItemsSource as ObservableCollection<Web.EMP_TABLE>;

When you use "as" instead of (TYPE) to cast, no exception is thrown if the cast fails. Your variable is simply set to null. Your cast is failing.


After your edit and reading of the comments, I don't see, how this should work:
As others have pointed out, your cast is failing.
You say, you pass an ObservableCollection, but in fact, you don't do it, have a look here:
In your ctor:

dataGrid1.ItemsSource = l.Entities;

l.Entities is most likely an IQueryable, not an ObservableCollection

Later, you are trying to cast dataGrid1.ItemsSource, which is failing. You showed us the code of GetEMP_TABLE_OBV which returns an ObservableCollection, but I don't see any usage of that method.


datagrid1.ItemSource is not an ObservableCollection so your cast fails and good is therefor null.

You have to inspect what type datagrid1.ItemSource actually hold (it is the type of the Entities property on the LoadOperation type ) and cast to that type

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号