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

c# entity entity-framework frame wpf

Question

I am attempting to utilize data grid as my Order Entry Control for User to input Products Order while working on POS application utilizing SQL CE, WPF, and Entity framework 3.5sp2. I want to tie this into my whole work paradigm, and I'm seeking for two-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 this is how my xaml code looks.

   <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 adjustments suggested by @vorrtex, however I later added a second button to save the changes, and I added the following code to the button click event, but the update failed.

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

Popular Answer

You are having an issue with this code:

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

This anonymous class's properties are read-only, therefore you should create a real class with them instead.

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