简体   繁体   中英

WPF Entity framework datagrid refresh

I started a new WPF project and on main Window I have a button. When I click it, I show a new window that displays as follows: 1 textBox (named tbTax) 1 Add Button 1 DataGrid (named dbGrid)

I obtained the DataGrid, by going to DataSources tab, and DRAG/DROP from there a table on the form/window. When I run the app, it all works as planned. In the second window I see in the grid all my records from the database table.

NOW: I did the Adding code for the "Add button". So when the user enters some text in the textBox (tbTax) and clicks on the Add button, the following code follows:

 using (MyEntities context = new MyEntities())
            {
                TAX tax = new TAX();
                tax.TAX1 = decimal.Parse(tbTax.Text);
                context.TAXs.Add(tva);
                context.SaveChanges();
                tbTax.Text = "";
                dbGrid.Items.Refresh();
            }

So it should be obvious: I add an item to the database table through the entity framework. But even if I added the refresh part at the end of the code... the grid does not refresh. So only if I exit the window and re-show it, only then I can see the new item I just Added.

EDIT Following the drag/drop I ended up with this:

--XAML--

 <DataGrid x:Name="tAXDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding}" Margin="10,157,10,35" RowDetailsVisibilityMode="VisibleWhenSelected">
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="tAXColumn1" Binding="{Binding TAX}" Header="TAX" Width="SizeToHeader"/>
            </DataGrid.Columns>
        </DataGrid>

--XAML.cs--

  private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            TestXXX.ArtDataSet artDataSet = ((TestXXX.ArtDataSet)(this.FindResource("artDataSet")));
            // Load data into the table TAX. You can modify this code as needed.
            TestXXX.ArtDataSetTableAdapters.TAXTableAdapter artDataSetTAXTableAdapter = new TestXXX.ArtDataSetTableAdapters.TAXTableAdapter();
            artDataSetTAXTableAdapter.Fill(artDataSet.TAX);
            System.Windows.Data.CollectionViewSource tAXViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("tAXViewSource")));
            tAXViewSource.View.MoveCurrentToFirst();
        }

Also, my Context is declared separately

namespace TestXXX
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class ArtEntities : DbContext
    {
        public ArtEntities()
            : base("name=ArtEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<BOOK> BOOKs { get; set; }
        public DbSet<TAX> TAXs { get; set; }
    }
}

and the TAX class is

namespace TestXXX
{
    using System;
    using System.Collections.Generic;

    public partial class TAX
    {
        public TAX()
        {
            this.BOOKs = new HashSet<BOOK>();
        }

        public int ID { get; set; }
        public Nullable<decimal> TAX1 { get; set; }

        public virtual ICollection<BOOK> BOOKs { get; set; }
    }
}

What is wrong with this? How can I fix it?

First of all, I assume you are only in a learning stage, as putting all layers into UI control is not a good idea. Data layer (communication with database) should be separated from model and model should be separated from view. There is of course many other designs, but separation is a core issue in all of them.

As you are using WPF, you should know the ObservableCollection contained in System.Collection.ObjectModel. This collection notifies data user (mostly UI controls in wpf) about changes in collection as adding, removing etc.

So what you need to do is set ItemSource of DataGrid with ObservableCollection. All you need to do next is only add tax item into this collection and save it to the database. Nothing more.

The solution seems to be simple after all... In the CS file of the Window

 public partial class NewTAX : Window
    {
        ArtEntities db;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            db = new ArtEntities();
            dbgrid.ItemsSource = db.TAXs.ToList();
        }

... then after adding a new item, just set the ItemSource AGAIN like:

        using (MyEntities context = new MyEntities())
        {
            TAX tax = new TAX();
            tax.TAX1 = decimal.Parse(tbTax.Text);
            context.TAXs.Add(tva);
            context.SaveChanges();
            tbTax.Text = "";
            dbgrid.ItemsSource = db.TAXs.ToList();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM