Panindra
Panindra

Reputation: 303

i want to convert a dataset of a SDF database to obseravable collection in WPF

i am currently working with SQL CE & WPF . in the middle of coding i struck with no idea of converting the dataset of a Database to my observablecollection which is binds to the UI Controllers like Listbox and listview.

plz guide me , if possible with code !!

Upvotes: 1

Views: 1919

Answers (1)

devuxer
devuxer

Reputation: 42384

Let's say your DataSet contains a Table named Person and that Person has columns Id, Name, and Age.

You first create a Person class to hold your Person data:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

Then you use LINQ to populate your ObservableCollection:

var people = new ObservableCollection<Person>(
    dataset.Tables["Person"].AsEnumerable().Select(p => new Person
    {
        Id = p.Field<int>("Id"),
        Name = p.Field<string>("Name"),
        Age = p.Field<int>("Age")
    }));

You will need to add the following assembly reference to your project in order to use the AsEnumerable<T>() and Field<T>() extension methods:

System.Data.DataSetExtensions (in System.Data.DataSetExtensions.dll)

Edit

In response to your comment, you would normally process each change you make to the data immediately rather than try to convert the whole ObservableCollection back to the DataSet. So, for example, if you add a new Person to your ObservableCollection, you would also want to add that Person to the DataSet.

Add a person:

var table = dataSet.Tables["Person"];
var row = table.NewRow();
row["Id"] = person.Id;
row["Name"] = person.Name;
row["Age"] = person.Age;
table.Rows.Add(row);

Delete a person:

var table = dataSet.Tables["Person"];
var row = table.AsEnumerable().Where(p => p.Id == person.Id);
row.Delete();

Update a person (say you want to change the age to 37):

var table = dataSet.Tables["Person"];
var row = table.AsEnumerable().Where(p => p.Id == person.Id);
var row["Age"] = 37;

You might also want to look into LINQ to SQL because it automates a lot of this stuff.

Upvotes: 2

Related Questions