简体   繁体   中英

c# WPF if statement for a check box and button press

Im looking to write an if statement for when a checkbox is checked and a button is pressed then do something however i can't get the if statement to work.

This is the code i have so far

 if (GPBox.IsChecked == true  && SearchButton.MouseUp == true )
        {
            connect = new MySqlConnection(connectionString);
            cmd = new MySqlCommand("select distinct * from gpSurgery", connect);
            connect.Open();
            DataTable dt = new DataTable();
            dt.Load(cmd.ExecuteReader());
            connect.Close();
            DataGrid1.DataContext = dt;
        }  

That code should go on to MouseUp event of the button, and then you don't need

&& SearchButton.MouseUp == true

You could add the mouseup event in xaml where your button is.

In the event handler you would write:

 if (GPBox.IsChecked == true)
    {
        connect = new MySqlConnection(connectionString);
        cmd = new MySqlCommand("select distinct * from gpSurgery", connect);
        connect.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        connect.Close();
        DataGrid1.DataContext = dt;
    }  

Why you not change it instead of the MouseUp to the Button_Click

 private void Button_Click(object sender, RoutedEventArgs e)
 {
     if (GPBox.IsChecked == true)
     {
         connect = new MySqlConnection(connectionString);
         cmd = new MySqlCommand("select distinct * from gpSurgery", connect);
         connect.Open();
         DataTable dt = new DataTable();
         dt.Load(cmd.ExecuteReader());
         connect.Close();
         DataGrid1.DataContext = dt;
      }
}  

My testing code XAML

<StackPanel>
    <CheckBox x:Name="GPBox"/>
    <Button Click="Button_Click"/>
</StackPanel>

Code behind:

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (GPBox.IsChecked == true)
        MessageBox.Show("222");
}

I hope it is enough to get you started.

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