Search code examples
mysqlwpfdatagridwindow

Update datagrid in WPF window (not MainWindow) from another one. *Without using MVVM*


I have a Window1 which contains a datagrid that is filled with MYSQL Database when Window1 is loaded, but to make an update there's this Window2 that contains textboxes in order to save the new information in MYSQL Database. I can update the information after I open and close Window2 as I show below:

Window2.ShowDialog();

//refreshing datagrid

Mouse.OverrideCursor = System.Windows.Input.Cursors.AppStarting;
dtCustomers = AdminDB.Get_Table("SELECT id, name FROM engcustomers", db.MySqlCon);
dataGrid.DataContext = dtCustomers;
MessageBox.Show("The information has been updated correctly");
Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;

And this works perfectly, the issue comes when in Window2 I press the button "Cancel" because I do not want to update anything, but due to my code, the query is executed anyway. That's why I need your support/help to update the datagrid in Window1 from Window2.

Could you pleeease help me?

Thank you in advance guys!


Solution

  • The ShowDialog() method returns a bool? that you can set in the Window2 before you close it and then use to determine whether the operation was cancelled in Window1:

    bool? cancelled = Window2.ShowDialog();
    
    if (cancelled != true)
    {
        //refreshing datagrid
    
        Mouse.OverrideCursor = System.Windows.Input.Cursors.AppStarting;
        dtCustomers = AdminDB.Get_Table("SELECT id, name FROM engcustomers", db.MySqlCon);
        dataGrid.DataContext = dtCustomers;
        MessageBox.Show("The information has been updated correctly");
        Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
    }
    

    Window2:

    private void Cancel_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = true;
        Close();
    }