I have 2 Windows, Main window has a button that opens Window 2.
Windows 2 contains datagrid holding a list of values, The user double-click to select a row from the list and closes Window 2 filling some text boxes with the data of the selected row
Some example code I have:
public class User {
public string FirstName {get; set;}
public string LastName { get; set;}
}
private void Button_Click(object sender, KeyEventArgs e) {
Window2 window = new(DataToRetrieve);
window.ShowDialog();
//Get data here to and print in the text boxes
//textbox.Text = itemRetrieved.Something;
}
My method for grabbing the item from the datagrid with MouseDoubleClick event
private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
if (sender != null)
{
DataGrid grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
DataRowView dr = (DataRowView)dgr.Item;
}
}
}
How should able to send over my main window the data of the list picked to my main window?
You could for example add a property to the second window where you store the selected data, e.g.:
public DataRowView SelectedData { get; private set; }
private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (sender != null)
{
DataGrid grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
this.SelectedData = (DataRowView)dgr.Item;
}
}
}
Then you just use this property in the MainWindow
:
private void Button_Click(object sender, KeyEventArgs e)
{
Window2 window = new(DataToRetrieve);
window2.ShowDialog();
// Get data here...
textbox.Text = window2.SelectedData["someColumn"].ToString();
}