How can I update the label value when the value changes?

I am trying to update "Player's health." when "Player" attacks a target. Player's health is reduced based on the target's return damage.

My Game class (where the label is):

public partial class Game : Form
{
    public static Wizard wizard;
    public static Assasin assasin;

    public Game()
    {
        InitializeComponent();
    }

    private void Battle_Click(object sender, EventArgs e)
    {
        Battle battle = new Battle();
        battle.Show();
    }

    public void Game_Load(object sender, EventArgs e)
    {
        NameLabel.Text = HeroMaker.className;
        if (HeroMaker.wizardChoosen)
        {
            wizard = new Wizard(HeroMaker.className);
            HealthLabel.Text = wizard.Health.ToString();
            DamageLabel.Text = wizard.AttackDamage.ToString();
            HealthBar.Maximum = wizard.Health;
            HealthBar.Value = wizard.Health;
        }

    }
}

My Battle class (when attacking is happening) :

 public partial class Battle : Form
{
    Creature troll = CreaturesFactory.CreateCreature(CreatureType.Troll);
    public Battle()
    {
        InitializeComponent();
    }

    private void AttackTroll_Click(object sender, EventArgs e)
    {
        Game.wizard.Health -= troll.ReturnDamage;
        //TODO: Update the "HealthLabel value."
    }
}

The problem is that when I attack the troll, Player's health is decreasing but its not updating on the label. Thanks in advance.

Upvotes: 0

Views: 615

Answers (1)

levelonehuman
levelonehuman

Reputation: 1505

You just need to update the label:

private void AttackTroll_Click(object sender, EventArgs e)
{
    Game.wizard.Health -= troll.ReturnDamage;
    //TODO: Update the "HealthLabel value."
    HealthLabel.Text = wizard.Health.ToString();
    //any other things that need to be updated
}

You can also bind the label value like in this question.

Similarly, you can hook up an event such as OnWizardHealthChange that updates the label value whenever the HP changes. This way, you won't need to remember to add HealthLabel.Text = wizard.Health.ToString(); everywhere the health changes. There's an example of this in the question that I linked.

EDIT:

You can try looking in the code-behind where the label is created to see its access modifier (is it public?)

Or, you can try this:

Label healthLabel = (Label)Application.OpenForms["FormName"].Controls.OfType<Label>().First(x=> x.Name == "LabelName");

Note that I haven't tested it but you should be able to at least get the label using this code and then update the value there. Here is a good discussion on accessing controls (such as your label) in another form.

Upvotes: 1

Related Questions