I have one wpf form with a DataGrid
and another wpf form with TextBoxes
.
I'm trying to pass each value of each cells of the selected row to the other form but i don't know how to do this with a wpf.
In the wpf Form2 i want to put these values into TextBox
for edit and then update the row of the Form1 and so the connected DataSet
.
How to solve this problem ?
Thanks
It looks like you are using a DataSet
for your DataGrid
.
Get the selected row (SelectedItem
) using Binding
.
Send this ChosenItem as ref
to the other form/window.
Set this sent ChosenItem
as the DataContext
of form grid.
Now, when you change the values in your Form2, changes will be reflected back in form1.
Eg code,
Form1
<Grid>
<DataGrid x:Name="Dgrid" HorizontalAlignment="Left" Margin="10,31,0,0" VerticalAlignment="Top" SelectedItem="{Binding ChosenItem}" />
<Button Content="Edit" HorizontalAlignment="Left" Margin="10,4,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
</Grid>
Form1 code-behind
public partial class MainWindow : Window
{
DataStore ds = new DataStore();
public MainWindow()
{
InitializeComponent();
Dgrid.DataContext = ds;
Dgrid.ItemsSource = ds.DataSource.Tables[0].DefaultView;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
DataRowView item = ds.ChosenItem;
Window1 w = new Window1(ref item); // send selected row as ref to other form
w.Show();
}
}
public class DataStore
{
public DataRowView ChosenItem { get; set; }
public DataStore()
{
DataTable table1 = new DataTable();
table1.Columns.Add(new DataColumn("Name", typeof(string)));
table1.Columns.Add(new DataColumn("Address", typeof(string)));
DataRow row = table1.NewRow();
row["Name"] = "Name1";
row["Address"] = "203 A";
table1.Rows.Add(row);
row = table1.NewRow();
row["Name"] = "Deepak";
row["Address"] = "BHEL Bhopal";
table1.Rows.Add(row);
ds.Tables.Add(table1);
}
DataSet ds = new DataSet();
public DataSet DataSource { get { return ds; } }
}
Form2
<Grid x:Name="FormGrid" DataContext="{Binding SelectedItem, ElementName=Dgrid}">
<TextBox HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width="120"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="0,49,0,0" TextWrapping="Wrap" Text="{Binding Address}" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="0,100,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
Form2 code-behind
public Window1(ref DataRowView item)
{
InitializeComponent();
FormGrid.DataContext = item;
}