Search code examples
wpfnulldialoglabelbox

Null Label Content in DialogBox (WPF)


I am a beginner in WPF. I have an application with a main window and a dialog box. When I the load dialog box, I put a number (fetched from database) in the content of a label in my dialog box. Everything goes well, and I can see the fetched number, in label of the dialog box, but when I try to use it for fetching some data in my dialog box, WPF says the label content is null. I put a number as content of the idNum. It worked properly. So I think there is no problem for my codes, but I can't understand why it is "null" although it is shown in dlg.lbId.

In my code behind of my main window I have:

    private void btManage_Click(object sender, RoutedEventArgs e)
    {
        var selected = lvOwnerCar.SelectedItem as Owner;
        int selectedId = selected.Id;
        string selectedName = selected.Name;
        CarsDialog dlg = new CarsDialog();
        dlg.lbName.Content = selectedName;
        dlg.lbId.Content = selectedId;
        dlg.Owner = this;
        dlg.ShowDialog();
    }

and in the code behind of dialog box I have:

        public CarsDialog()
    {
        InitializeComponent();
        ctx = new CarDbContext();
        lvCars.ItemsSource = (from c in ctx.Cars select c).ToList<Car>();
        int idNum = Convert.ToInt32(lbId.Content);
        lvCars.ItemsSource = (from c in ctx.Cars where c.Owner.Id == idNum select c).ToList<Car>();

    }

Solution

  • The issue can be that you are trying to read lbId.Content before it's really set. Try to move loading data from the constructor of CarsDialog to a method let's LoadData. Call LoadData before ShowDialog. You can get rid of the line lvCars.ItemsSource = (from c in ctx.Cars select c).ToList<Car>(); and keep only the second query.

    CarsDialog code behind:

    public CarsDialog()
    {
        InitializeComponent();
    }
    
    public void LoadData()
    {
        ctx = new CarDbContext();
        int idNum = Convert.ToInt32(lbId.Content);
        lvCars.ItemsSource = (from c in ctx.Cars where c.Owner.Id == idNum select c).ToList<Car>();
    }
    

    MainWindow code behind:

    private void btManage_Click(object sender, RoutedEventArgs e)
    {
        var selected = lvOwnerCar.SelectedItem as Owner;
        int selectedId = selected.Id;
        string selectedName = selected.Name;
        CarsDialog dlg = new CarsDialog();
        dlg.lbName.Content = selectedName;
        dlg.lbId.Content = selectedId;
        dlg.Owner = this;
        dlg.LoadData();
        dlg.ShowDialog();
    }