I am new to C# WPF and I am creating an application to add Item details to a form. My problem is I want to add item details from a wpf window to a datagrid which is in the main window. I created a class and add properties to set and get values. but I cannot get returns to main window from class. And I want to add those items to the datagrid too. [
Class Code:
public class AddItemToPRGrid
{
public string ItemNo { get; set; }
public string ItemName { get; set; }
public int Qty { get; set; }
public DateTime expDate { get; set; }
}
Add Items Window Code:
public partial class PnlAddItem : Window
{
public PnlAddItem()
{
InitializeComponent();
}
public static string no;
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
AddItemToPRGrid addItemToPRGrid = new AddItemToPRGrid();
addItemToPRGrid.ItemNo = txtItemNo.Text;
addItemToPRGrid.ItemName = txtItemName.Text;
addItemToPRGrid.Qty = Convert.ToInt32(txtItemQty.Text);
addItemToPRGrid.expDate = (DateTime)dpItemExpDate.SelectedDate;
this.Visibility = Visibility.Hidden;
}
}
Main Window Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnCreatePR_Click(object sender, RoutedEventArgs e)
{
AddItemToPRGrid addItemToPRGrid = new AddItemToPRGrid();
//This MessageBox is used to identify whether the value is return from class
MessageBox.Show(addItemToPRGrid.ItemNo);
}
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
PnlAddItem AddItemWindow = new PnlAddItem();
AddItemWindow.ShowDialog();
}
}
XAML Code:
<Grid Height="250">
<DataGrid x:Name="dataGridAddItem"
CanUserAddRows="True"
ColumnWidth="*">
<DataGrid.Columns>
<DataGridTextColumn Header="Item No" Binding="{Binding ino}"/>
<DataGridTextColumn Header="Item Name" Binding="{Binding iname}"/>
<DataGridTextColumn Header="Quantity" Binding="{Binding qty}"/>
<DataGridTextColumn Header="Expiry Date" Binding="{Binding expirydate}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
CodePudding user response:
you can return result via property:
public partial class PnlAddItem : Window
{
public PnlAddItem()
{
InitializeComponent();
}
public AddItemToPRGrid Item { get; private set; }
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
Item = new AddItemToPRGrid
{
ItemNo = txtItemNo.Text,
ItemName = txtItemName.Text,
Qty = Convert.ToInt32(txtItemQty.Text),
expDate = (DateTime)dpItemExpDate.SelectedDate
};
this.Close();
}
}
then add it to DataGrid:
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
var AddItemWindow = new PnlAddItem();
AddItemWindow.ShowDialog();
if (AddItemWindow.Item != null)
{
// add to datagrid, e.g. MainDataGrid.Items.Add(AddItemWindow.Item);
}
}