Is it possible to do 2-way databinding using Entity Framework and WPF DataGrid?

c# entity entity-framework frame wpf

Question

i am working on POS application using SQL CE , WPF , Entity framework 3.5sp2 and iam trying to use data grid as my Order Entry Control for User to enter Products Order . Iam plannning to bind this to enitiy frmae work model , abd looking for 2 way updating ?

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        using (MasterEntities nwEntities = new MasterEntities())
        {
          var users = from d in nwEntities.Companies
        select new CompanyRowModel{ CompanyId = d.CompanyId, CompanyName       d.CompanyName, Place = d.Place }

              listBox1.DataContext = users;
              dataGrid1.DataContext = users;
        }           
      }

      public class CompanyRowModel
      {
        public int CompanyId { get; set; }
        public string CompanyName { get; set; }
        public string Place{ get; set; }
      }

and my xaml coding goes like this

   <Grid>
     <ListBox Name="listBox1" ItemsSource="{Binding}"  />
    <Button Content="Show "  Name="button1" Click="button1_Click"  />

    <DataGrid AutoGenerateColumns="False" Name="dataGrid1" ItemsSource="{Binding}" >
      <DataGrid.Columns>
          <DataGridTextColumn Header=" ID"     Binding="{Binding CompanyId}"/>
          <DataGridTextColumn Header="Company Name"  Binding="{Binding CompanyName}"/>
          <DataGridTextColumn Header="Place"    Binding="{Binding Place}" />
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Save"  Name="button2" VerticalAlignment="Bottom" Click="button2_Click" />
</Grid>

EDITED :

i made the changes shown by @vorrtex, But, then i added another button to save the chages and in button click event i added follwing code , butit showing Updating error

  private void button2_Click(object sender, RoutedEventArgs e)
    {
         nwEntities.SaveChanges();
    }
1
2
1/1/2011 12:56:14 PM

Popular Answer

You have a problem with this code:

select new { d.CompanyId, d.CompanyName, d.Place }

Properties in this anonymous class are read-only, so you should create a real class with these properties.

public class CompanyRowModel
{
    public int CompanyId { get; set; }
    //...
}
//...
var users = from d in nwEntities.Companies
            select new CompanyRowModel{ CompanyId = d.CompanyId, CompanyName = d.CompanyName, Place = d.Place }
1
1/1/2011 12:38:31 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow