Catquatwa
Catquatwa

Reputation: 1739

Add Numbers to Labels in Windows Forms

I have a windows form application (Visual Studio C#) I have been working on, and I want to add numbers to a label. This is the code I have come up with so far:

private int _180;

private void Btn_Click(object sender, EventArgs e)
{
    _180 = 180;
    Lbl_Money.Text +=180;
}

The Money label was '360', but when I do this it puts the label to '360180'. How can I add numbers to the label so it will reach 540?

Upvotes: 0

Views: 4249

Answers (3)

Tarik
Tarik

Reputation: 11209

You need to parse lbl_money.text to int:

Lbl_money.text = Integer.Parse (Lbl_money.text) +180

Note however, that you would be better off keeping the value in an integer variable and reflecting it as needed in the label. You can use a property at the form level to hide the details.

private int _money

Public money {
    get {
        return _money;
    }

    set (int value) {
        _money = value;
        Lbl_Text = _money;
    }
}

Upvotes: 0

Slashy
Slashy

Reputation: 1881

The Label's text is a string type so you should do a simple conversion:

 _180 = 180;
  int value=Convert.ToInt32(Lbl_Money.Text); 
 value+=180;
Lbl_Money.Text =value;

Upvotes: 0

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9201

The two numbers are getting concatenated together because the Lbl_Money.Text property is a string, not a number.

In order to add the two together, you need to convert your label to a number. After that, you need to set it back as a string to re-assign it back to the label.

Lbl_Money.Text = (Convert.ToInt32(Lbl_Money.Text) + 180).ToString();

A better solution would be to store your total as a variable, and use that variable as the source of your label:

private int _180;
private int _money;

private void Btn_Click(object sender, EventArgs e)
{
    _180 = 180;
    _money += 180;
    Lbl_Money.Text = money.ToString();
}

Upvotes: 2

Related Questions