Thursday, August 20, 2009

WPF binding to a typed dataset

I having been learning WPF and came across a problem trying to use typed datasets and the Visual Studio wizard for generating the xsd file. Once I created the dataset (xsd file) I couldn't find a way to actually bind it to anything or get the data. After some trial and error, the following seems to work well. I am populating an Xceed datagrid but the code is generic. I want to provide a 'blank' row for adding new records as well.


public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{

// Customers table (dataset is 'dsCustomers' as found in the ...Designer.cs file)
m_customer = new dsCustomers.TblCustomers();
//Create data adapter and fill from the source table
(new dsCustomersTableAdapters.TblCustomersTableAdapter()).Fill(m_customer );

m_customer.Rows.Add(m_customer.NewRow()); // Add a blank row

// Likewise for Address table (more verbose)

m_Addresses= new dsCustomers.TblAddresses();
dsCustomersTableAdapters.TblAddressesTableAdapter tblAdap = new dsCustomersTableAdapters.TblAddressesTableAdapter();

tblAdap.Fill(m_Addresses);
DataRow dr = m_Addresses.NewRow(); // generate a new row
m_Addresses.Rows.Add(dr); // append back to the table

base.OnStartup(e);
}

private dsCustomers.TblCustomers m_customer ;

public dsCustomers.TblCustomers Customers
{
get
{
return m_customer ;
}
}
private dsCustomers.TblAddresses m_Addresses;

public dsCustomers.TblAddresses Addresses
{
get
{
return m_Addresses;
}
}
}





Meanwhile the xaml is ..

< Grid.Resources>

< xcdg:DataGridCollectionViewSource
x:Key="Tblmycustomers"
Source="{Binding Source={x:Static Application.Current},
Path= Customers}"/ >

< xcdg:DataGridCollectionViewSource
x:Key="TblLocations"
AutoCreateForeignKeyDescriptions="true"
Source="{Binding Source={x:Static Application.Current},
Path= Addresses}"/ >
< /Grid.Resources >