Home > Mobile >  Show Balance after user is selected
Show Balance after user is selected

Time:12-06

            var user = (User)cbUser.SelectedItem;
            tbBalance.Text = "Balans: "   user.Balance.ToString();

So I want to use this code to print the balance of each user for a gambeling app. Only the problem is that this gives me an error before the app starts saying user is null. Is there a way to run this code after the user is selected. My user can be selected in a combobox in a xaml application binded to my User class.

I tried to use a AfterSelected method but this gave me weird errors and I really don't how to use such a method.

CodePudding user response:

You can also reset the text when there's nothing selected.

var user = (cbUser as User)?.SelectedItem;
tbBalance.Text = $"Balans: {user?.Balance ?? "N/A"}";

This means that if nothing is selected, the balance text would be "Balans: N/A".

This code will also ensure that no nasty "object reference not set to an instance of an object" errors are thrown.

CodePudding user response:

Use defensive coding, one way is below.

var user = (User)cbUser?.SelectedItem;
if(user != null)
{
    tbBalance.Text = "Balans: "   user.Balance.ToString();
}

That means whether the user is null then this code will not execute, otherwise it will execute.

  •  Tags:  
  • c#
  • Related