How to pass a command parameter to a button

I want to pass assign_id, which is the parameter of the myButton command for the .cs file to update the values ​​in the database. I wrote this code, but when I clicked on myButton, it showed a message box that the method and operation failed. How can I solve this problem?

private void Command(Int32 parameter) { p = parameter; } private void btnUpdate_Click(Object sender, RoutedEventArgs e) { try { SqlConnection con = new SqlConnection("server=(local); Integrated Security=true; Database=nrcs"); con.Open(); SqlCommand comm = new SqlCommand("UPDATE Assignments SET assignment_title='myassignment' WHERE assignment_id=" + p + ";", con); comm.ExecuteNonQuery(); con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } 

Here's the Xaml Code:

 <Button x:Name="myButton" Content="update" Command="{Binding Command}" CommandParameter="{Binding assignment_id}" Click="btnUpdate_Click" ></Button> 
+4
source share
1 answer

I think this is the order in which the click event (btnUpdate_Click) is fired and the command. If the event is fired first, the variable 'p' does not matter, and the request fails.

I think you should use either an event or a command to execute the request, and not both of them. if you intend to continue to use the MVVM template (which I recommend), use the command in another class, which will be your view model.

0
source

Source: https://habr.com/ru/post/1486781/


All Articles