Fill observableCollection directly from sql server

此生再无相见时 提交于 2019-12-10 12:08:00

问题


I would like to know if there is any way to fill ObservableCollection directly from SQL server. Currently I am loading my data into DataTable (using sqlDataAdapter) and do a conversion to ObservableCollection manually and it very inefficient.

How it can be done?


回答1:


OK, I have found a way to do this:

It can be done using SqlDataReader.

public ObservableCollection<DataItem> LoadCategoriesData()
{
    Command = new SqlCommand(StoredProcedure, Connection);
    Command.CommandType = CommandType.StoredProcedure;
    ObservableCollection<DataItem> myColl = new ObservableCollection<DataItem>();
    Connection.Open();
    SqlDataReader reader = Command.ExecuteReader();
    while (reader.Read())
    {
        int mainCatID = reader.GetInt32(0);
        string categoryName = reader.GetString(1);
        //adding row data to observable
        myColl.Add(new DataItem(mainCatID, categoryName));
    }
    Connection.Close();
    return myColl;
}


来源:https://stackoverflow.com/questions/14179967/fill-observablecollection-directly-from-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!