Как вызвать метод из UserControl при закрытии окна - PullRequest
0 голосов
/ 26 апреля 2020

В моем UserControl есть метод, который я хотел бы вызвать при закрытии моего окна.

У меня есть DataGrid на моей странице UserControl, которая при двойном щелчке открывает новый Window и заполняет данные выбранной строки из UserControl в Textboxes в Window ,

У меня на странице UserControl есть метод, который загружает DataGrid, и я хотел бы вызвать этот метод, когда мой Window закрывается.

Ниже приведен код для загрузки моей DataGrid при загрузке моей страницы UserControl:

        public void DataGridData()
    {

            // Attemption to connect to SQL Server database and populate DataGrid with database tables. 
            try
            {
                string connectionString = ("Data Source=WINDOWS-B1AT5HC\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");
                SqlConnection connection = new SqlConnection(connectionString);

                // Review SQL queries for security vulnerabilities
                SqlCommand cmd = new SqlCommand("SELECT [hb_Disputes].[DSP_ID], [hb_disputes].[ACCOUNT], [Users].[TX_EMPLOYEE], [hb_CsrNames].[NM_USER], [hb_disputes].[CUST_NAME],[hb_disputes].[PREM_ADDR], [hb_status].[Status], [hb_disputes].[OPENED], [hb_disputes].[DEADLINE], [hb_disputes].[DATERSLVD], [hb_disputes].[PRMCAUSE], [hb_disputes].[RPTTYPE], [hb_ratetype].[RateType], [hb_Disputes].[FR_DT_FIRSTREV], [hb_Disputes].[FR_TS_LATESTUPD], [hb_Disputes].[COMMENT], [hb_Disputes].[FR_DSP_CLSF], [hb_Disputes].[FINADJ], [hb_Disputes].[CALLRSN], [hb_Disputes].[SECCAUSE], [hb_Disputes].[MTR], [hb_Disputes].[SERTYPE], [hb_Disputes].[FR_CUST_CNTCT], [hb_Disputes].[FR_WRK_REQ], [hb_Disputes].[FR_OPN_ERR], [hb_Disputes].[FR_SO_TP], [hb_Disputes].[FR_SO_DTLS], [hb_Disputes].[FR_SO_DT_WNTD], [hb_Disputes].[FR_SO_ISSD_BY], [hb_Disputes].[FR_CMMNT], DATEDIFF(day,[OPENED], [DEADLINE]) AS DaysOpen FROM [hb_disputes]" +
                    " LEFT JOIN [Users] ON [hb_disputes].[ASSGNTO] = [Users].[KY_USER_ID] LEFT JOIN [hb_CsrNames] ON [hb_disputes].[WFMUSER] = [hb_CsrNames].[KY_USER_ID] LEFT JOIN [hb_status] ON [hb_disputes].[STATUS] = [hb_status].[STSID] LEFT JOIN [hb_ratetype] ON [hb_disputes].[REV_CLS] = [hb_ratetype].[RTID] Where [hb_disputes].[STATUS]= 3 AND [Users].[TX_EMPLOYEE] = '" + Environment.UserName + "'", connection);
                // Review SQL queries for security vulnerabilities
                connection.Open();
                DataTable dt = new DataTable();

                dt.Load(cmd.ExecuteReader());
                connection.Close();

                dtGrid.DataContext = dt;

                // Focus in on line 1 of the data grid on UserControl load 
                // So it can be shown in the key information side column

            }
            catch (Exception ex)
            {
                 MessageBox.Show(ex.Message);
            }

    }

Ниже приведен код, который я написал для обновления базы данных, когда Window закрывается. Затем пользователь возвращается на страницу UserControl, и я хотел бы от DataGrid до Load/Refresh. Код, который я написал для этого, (Application.Current.MainWindow as DataGrid_HBD).DataGridData(), но, конечно, он не работает, потому что я не вызываю метод из Window

        private void Window_HBD_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {

        SqlConnection con = new SqlConnection("Data Source=WINDOWS-B1AT5HC\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");

        try
        {
            SqlCommand cmd = new SqlCommand("UPDATE [hb_Disputes] SET FR_DSP_CLSF=@FR_DSP_CLSF, FR_CUST_CNTCT=@FR_CUST_CNTCT, FR_WRK_REQ=@FR_WRK_REQ, FR_OPN_ERR=@FR_OPN_ERR, FR_SO_TP=@FR_SO_TP, FR_SO_DTLS=@FR_SO_DTLS, FR_CMMNT=@FR_CMMNT, FR_SO_DT_WNTD=@FR_SO_DT_WNTD, FINADJ=@FINADJ, SERTYPE=@SERTYPE, CALLRSN=@CALLRSN, SECCAUSE=@SECCAUSE, MTR=@MTR, RPTTYPE=@RPTTYPE, PRMCAUSE=@PRMCAUSE, COMMENT=@COMMENT, FR_TS_LATESTUPD=@FR_TS_LATESTUPD WHERE DSP_ID=@DSP_ID", con);
            cmd.Parameters.AddWithValue("@DSP_ID", txt_RowRecrd.Text);

            // Second Row
            cmd.Parameters.AddWithValue("@FR_DSP_CLSF", cmb_DisputeClassification.SelectedValue);
            cmd.Parameters.AddWithValue("@FR_CUST_CNTCT", cmb_CustomerContact.SelectedValue);
            cmd.Parameters.AddWithValue("@FR_WRK_REQ", cmb_requestedwork.SelectedValue);
            cmd.Parameters.AddWithValue("@FR_OPN_ERR", cmb_OpenInError.SelectedValue);
            cmd.Parameters.AddWithValue("@FR_SO_TP", cmb_ServiceOrderType.SelectedValue);
            cmd.Parameters.AddWithValue("@FR_SO_DTLS", cmb_ServiceOrderDetails.SelectedValue);
            cmd.Parameters.AddWithValue("@FR_CMMNT", txt_ReviewNotes.Text);

            // Check if DatePicker has a selected date
            // if yes send date to Database 
            // if no send NULL to database
            if (DatePicker_ScheduledFor.SelectedDate == null)
            {
                cmd.Parameters.AddWithValue("@FR_SO_DT_WNTD", DBNull.Value);
            }
            else
            {
                cmd.Parameters.AddWithValue("@FR_SO_DT_WNTD", DatePicker_ScheduledFor.Text);

            }

            // Third Row
            cmd.Parameters.AddWithValue("@RPTTYPE", cmb_UtilityRptTyp.SelectedValue);
            cmd.Parameters.AddWithValue("@FINADJ", cmb_FinancialAdjustment.SelectedValue);
            cmd.Parameters.AddWithValue("@SERTYPE", cmb_ServiceTypeAdjustment.SelectedValue);
            cmd.Parameters.AddWithValue("@CALLRSN", cmb_InitialCallReason.SelectedValue);
            cmd.Parameters.AddWithValue("@PRMCAUSE", cmb_PrimCause.SelectedValue);
            cmd.Parameters.AddWithValue("@SECCAUSE", cmb_UnderlyingCause.SelectedValue);
            cmd.Parameters.AddWithValue("@MTR", cmb_MeterIssue.SelectedValue);
            cmd.Parameters.AddWithValue("@COMMENT", txt_ResolutionNotes.Text);
            cmd.Parameters.AddWithValue("@FR_TS_LATESTUPD", DateTime.Now);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            (Application.Current.MainWindow as DataGrid_HBD).DataGridData()

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

Ниже приведен код, который открывает мое новое окно ( Window1)

        private void dtGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        // Check to see if High Bill data entry form is open
        // If it is then bring it to focus
        // If it is not, then open that jawn 
        if (Application.Current.Windows.OfType<Window1>().Any())
        {
            Application.Current.Windows.OfType<Window1>().First().Activate();
        }
        else
        {
            // User double clicks on DataGrid Row
            // Open new Window
            // Populate selected textboxes with selected datarow
            DataGrid gd = (DataGrid)sender;
            DataRowView row_selected = gd.SelectedItem as DataRowView;

            var windowToOpen = new Window1();

            if (gd != null)
            {
                // Textboxes
                windowToOpen.txt_RowRecrd.Text = row_selected["DSP_ID"].ToString();
                windowToOpen.txt_acctnumber.Text = row_selected["ACCOUNT"].ToString();
                windowToOpen.txt_analyst.Text = row_selected["TX_EMPLOYEE"].ToString();
                windowToOpen.txt_custname.Text = row_selected["CUST_NAME"].ToString();
                windowToOpen.txt_address.Text = row_selected["PREM_ADDR"].ToString();
                windowToOpen.txt_Status.Text = row_selected["Status"].ToString();
                windowToOpen.txt_DaysOpen.Text = row_selected["DaysOpen"].ToString();
                windowToOpen.txt_revcls.Text = row_selected["RateType"].ToString();
                windowToOpen.txt_WFMissuedBy.Text = row_selected["NM_USER"].ToString();
                windowToOpen.txt_ReviewNotes.Text = row_selected["FR_CMMNT"].ToString();
                windowToOpen.txt_ResolutionNotes.Text = row_selected["COMMENT"].ToString();
                windowToOpen.DatePicker_ScheduledFor.Text = row_selected["FR_SO_DT_WNTD"].ToString();



                // Date Open Parse is needed for ShortDate format.
                if (row_selected["OPENED"] != null)
                {
                    DateTime dateTime;
                    if (DateTime.TryParse(row_selected["OPENED"].ToString(), out dateTime))
                    {
                        windowToOpen.txt_opened.Text = dateTime.ToShortDateString();
                    }
                    else
                    {
                        windowToOpen.txt_opened.Text = ""; //assign default value
                    }
                }

                // Deadline Parse is needed for ShortDate format.
                if (row_selected["DEADLINE"] != null)
                {
                    DateTime dateTime;
                    if (DateTime.TryParse(row_selected["DEADLINE"].ToString(), out dateTime))
                    {
                        windowToOpen.txt_deadline.Text = dateTime.ToShortDateString();
                    }
                    else
                    {
                        windowToOpen.txt_deadline.Text = ""; //assign default value
                    }
                }

                // Date Resolved Parse is needed for ShortDate format.
                if (row_selected["DATERSLVD"] != null)
                {
                    DateTime dateTime;
                    if (DateTime.TryParse(row_selected["DATERSLVD"].ToString(), out dateTime))
                    {
                        windowToOpen.txt_DateResolved.Text = dateTime.ToShortDateString();
                    }
                    else
                    {
                        windowToOpen.txt_DateResolved.Text = ""; //assign default value
                    }
                }

                // First Review Parse is needed for ShortDate format.
                if (row_selected["FR_DT_FIRSTREV"] != null)
                {
                    DateTime dateTime;
                    if (DateTime.TryParse(row_selected["FR_DT_FIRSTREV"].ToString(), out dateTime))
                    {
                        windowToOpen.txt_firstreview.Text = dateTime.ToShortDateString();
                    }
                    else
                    {
                        windowToOpen.txt_firstreview.Text = ""; //assign default value
                    }
                }
                // First Review Parse is needed for ShortDate format.
                if (row_selected["FR_TS_LATESTUPD"] != null)
                {
                    DateTime dateTime;
                    if (DateTime.TryParse(row_selected["FR_TS_LATESTUPD"].ToString(), out dateTime))
                    {
                        windowToOpen.txt_Latestupdate.Text = dateTime.ToShortDateString();
                    }
                    else
                    {
                        windowToOpen.txt_Latestupdate.Text = ""; //assign default value
                    }
                }


                // ComboBoxes
                SqlConnection connection = new SqlConnection("Data Source=WINDOWS-B1AT5HC\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");

                try
                {
                    // Dispute Classification ComboBox
                    SqlDataAdapter Status_data0 = new SqlDataAdapter("SELECT * FROM [hb_DspClsf]", connection);
                    DataSet ds0 = new DataSet();
                    Status_data0.Fill(ds0, "t");

                    windowToOpen.cmb_DisputeClassification.ItemsSource = ds0.Tables["t"].DefaultView;
                    windowToOpen.cmb_DisputeClassification.DisplayMemberPath = "TXT_DSP_CLSF";
                    windowToOpen.cmb_DisputeClassification.SelectedValuePath = "KY_DSP_CLSF";
                    windowToOpen.cmb_DisputeClassification.SelectedValue = row_selected["FR_DSP_CLSF"].ToString();

                    // Customer Contacts ComboBox
                    SqlDataAdapter Status_data1 = new SqlDataAdapter("SELECT * FROM [hb_CustCntct]", connection);
                    DataSet ds1 = new DataSet();
                    Status_data1.Fill(ds1, "t");

                    windowToOpen.cmb_CustomerContact.ItemsSource = ds1.Tables["t"].DefaultView;
                    windowToOpen.cmb_CustomerContact.DisplayMemberPath = "TXT_CUST_CNT";
                    windowToOpen.cmb_CustomerContact.SelectedValuePath = "KY_CUST_CNT";
                    windowToOpen.cmb_CustomerContact.SelectedValue = row_selected["FR_CUST_CNTCT"].ToString();

                    // Requested Work ComboBoxes
                    SqlDataAdapter Status_data2 = new SqlDataAdapter("SELECT * FROM [hb_WrkReq]", connection);
                    DataSet ds2 = new DataSet();
                    Status_data2.Fill(ds2, "t");

                    windowToOpen.cmb_requestedwork.ItemsSource = ds2.Tables["t"].DefaultView;
                    windowToOpen.cmb_requestedwork.DisplayMemberPath = "TXT_WRK_REQ";
                    windowToOpen.cmb_requestedwork.SelectedValuePath = "KY_WRK_REQ";
                    windowToOpen.cmb_requestedwork.SelectedValue = row_selected["FR_WRK_REQ"].ToString();

                    // Open In Error ComboBox
                    SqlDataAdapter Status_data3 = new SqlDataAdapter("SELECT * FROM [hb_OpenErr]", connection);
                    DataSet ds3 = new DataSet();
                    Status_data3.Fill(ds3, "t");

                    windowToOpen.cmb_OpenInError.ItemsSource = ds3.Tables["t"].DefaultView;
                    windowToOpen.cmb_OpenInError.DisplayMemberPath = "TXT_OPN_ERR";
                    windowToOpen.cmb_OpenInError.SelectedValuePath = "KY_OPN_ERR";
                    windowToOpen.cmb_OpenInError.SelectedValue = row_selected["FR_OPN_ERR"].ToString();

                    // Service Order Type Combobox
                    SqlDataAdapter Status_data4 = new SqlDataAdapter("SELECT * FROM [hb_SerOrdType]", connection);
                    DataSet ds4 = new DataSet();
                    Status_data4.Fill(ds4, "t");

                    windowToOpen.cmb_ServiceOrderType.ItemsSource = ds4.Tables["t"].DefaultView;
                    windowToOpen.cmb_ServiceOrderType.DisplayMemberPath = "TXT_SO_TP";
                    windowToOpen.cmb_ServiceOrderType.SelectedValuePath = "KY_SO_TP";
                    windowToOpen.cmb_ServiceOrderType.SelectedValue = row_selected["FR_SO_TP"].ToString();

                    // Service Order Details Combobox
                    SqlDataAdapter Status_data5 = new SqlDataAdapter("SELECT * FROM [hb_SerOrdDtls]", connection);
                    DataSet ds5 = new DataSet();
                    Status_data5.Fill(ds5, "t");

                    windowToOpen.cmb_ServiceOrderDetails.ItemsSource = ds5.Tables["t"].DefaultView;
                    windowToOpen.cmb_ServiceOrderDetails.SelectedValuePath = "KY_SO_DTL";
                    windowToOpen.cmb_ServiceOrderDetails.DisplayMemberPath = "TXT_SO_DTL";
                    windowToOpen.cmb_ServiceOrderDetails.SelectedValue = row_selected["FR_SO_DTLS"].ToString();

                    //Utility Report ComobBox
                    SqlDataAdapter Status_data6 = new SqlDataAdapter("SELECT * FROM [hb_RptType]", connection);
                    DataSet ds6 = new DataSet();
                    Status_data6.Fill(ds6, "t");

                    windowToOpen.cmb_UtilityRptTyp.ItemsSource = ds6.Tables["t"].DefaultView;
                    windowToOpen.cmb_UtilityRptTyp.DisplayMemberPath = "ReportType";
                    windowToOpen.cmb_UtilityRptTyp.SelectedValuePath = "RPTID";
                    windowToOpen.cmb_UtilityRptTyp.SelectedValue = row_selected["RPTTYPE"].ToString();

                    // Finacial Adjustment Combobox
                    SqlDataAdapter Status_data7 = new SqlDataAdapter("SELECT * FROM [hb_FinAdj]", connection);
                    DataSet ds7 = new DataSet();
                    Status_data7.Fill(ds7, "t");

                    windowToOpen.cmb_FinancialAdjustment.ItemsSource = ds7.Tables["t"].DefaultView;
                    windowToOpen.cmb_FinancialAdjustment.SelectedValuePath = "FNADJ_ID";
                    windowToOpen.cmb_FinancialAdjustment.DisplayMemberPath = "FinancialAdjustment";
                    windowToOpen.cmb_FinancialAdjustment.SelectedValue = row_selected["FINADJ"].ToString();

                    // Service Type Adjustment Combobox
                    SqlDataAdapter Status_data8 = new SqlDataAdapter("SELECT * FROM [hb_Service]", connection);
                    DataSet ds8 = new DataSet();
                    Status_data8.Fill(ds8, "t");

                    windowToOpen.cmb_ServiceTypeAdjustment.ItemsSource = ds8.Tables["t"].DefaultView;
                    windowToOpen.cmb_ServiceTypeAdjustment.SelectedValuePath = "SRVID";
                    windowToOpen.cmb_ServiceTypeAdjustment.DisplayMemberPath = "ServiceType";
                    windowToOpen.cmb_ServiceTypeAdjustment.SelectedValue = row_selected["SERTYPE"].ToString();

                    //// Initial Call Analysis Combobox
                    //SqlDataAdapter Status_datah = new SqlDataAdapter("SELECT * FROM [hb_Service]", connection);
                    //DataSet dsh = new DataSet();
                    //Status_datah.Fill(dsh, "t");

                    //windowToOpen.cmb_ServiceTypeAdjustment.ItemsSource = dsh.Tables["t"].DefaultView;
                    //windowToOpen.cmb_ServiceTypeAdjustment.SelectedValuePath = "SRVID";
                    //windowToOpen.cmb_ServiceTypeAdjustment.DisplayMemberPath = "ServiceType";
                    //windowToOpen.cmb_ServiceTypeAdjustment.SelectedValue = row_selected["WFMANAL"].ToString();

                    // Initial Call Reason Combobox
                    SqlDataAdapter Status_data10 = new SqlDataAdapter("SELECT * FROM [hb_CallRsn]", connection);
                    DataSet ds10 = new DataSet();
                    Status_data10.Fill(ds10, "t");

                    windowToOpen.cmb_InitialCallReason.ItemsSource = ds10.Tables["t"].DefaultView;
                    windowToOpen.cmb_InitialCallReason.SelectedValuePath = "CLRSN_ID";
                    windowToOpen.cmb_InitialCallReason.DisplayMemberPath = "CallReason";
                    windowToOpen.cmb_InitialCallReason.SelectedValue = row_selected["CALLRSN"].ToString();

                    // Meter Issue Reason Combobox
                    SqlDataAdapter Status_data11 = new SqlDataAdapter("SELECT * FROM [hb_MtrIss]", connection);
                    DataSet ds11 = new DataSet();
                    Status_data11.Fill(ds11, "t");

                    windowToOpen.cmb_MeterIssue.ItemsSource = ds11.Tables["t"].DefaultView;
                    windowToOpen.cmb_MeterIssue.SelectedValuePath = "MTRISID";
                    windowToOpen.cmb_MeterIssue.DisplayMemberPath = "MeterIssue";
                    windowToOpen.cmb_MeterIssue.SelectedValue = row_selected["MTR"].ToString();

                    // Primary Cause ComobBox
                    SqlDataAdapter Status_data12 = new SqlDataAdapter("SELECT * FROM [hb_PrimCause]", connection);
                    DataSet ds12 = new DataSet();
                    Status_data12.Fill(ds12, "t");

                    windowToOpen.cmb_PrimCause.ItemsSource = ds12.Tables["t"].DefaultView;
                    windowToOpen.cmb_PrimCause.DisplayMemberPath = "PrimaryCause";
                    windowToOpen.cmb_PrimCause.SelectedValuePath = "PRMCSID";
                    windowToOpen.cmb_PrimCause.SelectedValue = row_selected["PRMCAUSE"].ToString();

                    // Underlying Cause ComobBox
                    SqlDataAdapter Status_data13 = new SqlDataAdapter("SELECT * FROM [hb_SecCause]", connection);
                    DataSet ds13 = new DataSet();
                    Status_data13.Fill(ds13, "t");

                    windowToOpen.cmb_UnderlyingCause.ItemsSource = ds13.Tables["t"].DefaultView;
                    windowToOpen.cmb_UnderlyingCause.DisplayMemberPath = "SecondaryCause";
                    windowToOpen.cmb_UnderlyingCause.SelectedValuePath = "SECCS_ID";
                    windowToOpen.cmb_UnderlyingCause.SelectedValue = row_selected["SECCAUSE"].ToString();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

                // Open Window 1
                windowToOpen.Show();

            }
            else
            {
                return;
            }
        }
    }

1 Ответ

1 голос
/ 26 апреля 2020

Вы должны подписаться на событие Window.Closed:

private void dtGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
  var windowToOpen = new Window1();
  windowToOpen.Closed += UpdateView_OnWindowClosed;
  windowToOpen.Show();
}

private void UpdateView_OnWindowClosed(object sender, EventArgs e)
{
  var window = senbder as Window;
  window.Closed -= UpdateView_OnWindowClosed;

  DataGridData();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...