0

I am building a sale application on wpf and I have a datagrid that contains sales data and at each time I execute an insert, delete or update query, I have to perform the display query shown below, is there any way I can bind the datagrid directly to the SQL Server table, so that it's updated automatically when the SQL Server table is changed?

Code behind:

connection.open();

SqlDataAdapter adapter = new SqlDataAdapter("SELECT*FROM Comptoir", connection);
tble.Clear();
adapter.Fill(tble);

ComptoirGrid.ItemsSource = tble.DefaultView;
connection.close();
2
  • Bindings can update the data from code behind to xaml but call have to be dispatched for fetching the data from database. Commented Sep 30, 2018 at 18:03
  • Yes exactly, but how do I bind the datagrid to the database table in the code behind by setting trigger to be the table change. Commented Sep 30, 2018 at 20:01

2 Answers 2

1

try this

using (SqlConnection con = new SqlConnection(connection_string))
        {
            con.Open();
            // 2
            // Create new DataAdapter
            using (SqlDataAdapter a = new SqlDataAdapter(
                "SELECT * FROM Contacts", con))
            {
                // 3
                // Use DataAdapter to fill DataTable
                DataTable t = new DataTable();
                a.Fill(t);
                // 4
                // Render data onto the screen
                Data_table.DataSource = t;
            }
        }

put this whenever you take action to your SQL server database like when you edit your data pressed on save button or update put this code, reply what will happen with you. good luck bro 👍

Sign up to request clarification or add additional context in comments.

3 Comments

it appears to be somehow the same way of what I am currently using, I want to profit from the "Binding" fonctionnality of WPF so that I don't have to rewrite these commands each time.
did you tried datagridview.update(); or datagridview.refresh();
I am using WPF not WinFrom so the class is Datagrid (not datagridview) although it handles this methode Datagrid.items.refresh(); the items in the datagrid need to be binded first then to call for refresh or update.
0

I finanlly found the solution for it, and it's really this simple, adding a datasource to the database and then right click on the table you want and there you have a datagrid binding template already set, then you drag it to the location you want in the window, you will see the binding code on xaml automatically generated, I hope this will be helpfull.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.