1

I want to auto load some data from database to populate some text boxes and combo boxes when a new window is loaded.

For example when I click a button in window1, window1 will show a new window window2 and pass an ID to window2 (id is required for querying database). How can i do that?

Thanks,

Vasfed
  • 18,013
  • 10
  • 47
  • 53
BMA
  • 33
  • 6

3 Answers3

1

This is just a very simple example of what you can do:

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Name="btn1" Click="btn1_Click" Content="Button" Margin="10,10,361,283"></Button>
    </Grid>
</Window>

MainWindow.xaml.cs

  private void btn1_Click(object sender, RoutedEventArgs e)
        {
            Window2 win2 = new Window2(1);
            win2.Show();
        }

Window2.xaml

<Window x:Class="WpfApplication1.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window2" Height="300" Width="300">
    <Grid Margin="0,0,170,249">
        <TextBox Name="txtBox1" Margin="18,160,-18,-173"></TextBox>
        <TextBox Name="txtBox2" Margin="18,119,-18,-134"></TextBox>
        <TextBox Name="txtBox3" Margin="18,76,-18,-93"></TextBox>
        <TextBox Name="txtBox4" Margin="18,36,-18,-50"></TextBox>
    </Grid>
</Window>

Window2.xaml.cs

public partial class Window2 : Window
    {
        public Window2(int Id)
        {
            InitializeComponent();
            ReadDataFromDB(Id);
        }

        public void ReadDataFromDB(int Id)
        {

            //read your data
            txtBox1.Text = "Some value 1";
            txtBox2.Text = "Some value 2";
            txtBox3.Text = "Some value 3";
            txtBox4.Text = "Some value 4";
        }
    }
Zippy
  • 1,804
  • 5
  • 27
  • 36
1

1)Create ui elements in the window

2)Create a model class with the required fields.

3)While clicking the button in window1 pass the id to the constructor of the next window.

4).Using the id query the database based on your need.Get the results and bind the fields to the ui elements values.

5).These database querying and all can be written inside your constructor or window load event.

You can accomplish this using MVVM.No need to write excess code for setting the values to the ui.

VVN
  • 1,607
  • 2
  • 16
  • 25