简体   繁体   中英

C# label string to int conversion error

I am making a very small RPG game in C# to practice some skill (and to have fun!). I have gotten pretty far with the images, buttons and such. My issue is that I am being thrown an error when trying to convert my label strings into integers to be compared for my attackingPhase() method.

Here is my code and a screenshot of the error.

I believe my code is correct but I can not figure out as to why the error is being thrown.

Thank you for all help.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RPG
{
public partial class Form2 : Form
{
    private Form1 mainForm = null;

    public Form2(Form callingForm)
    {
        mainForm = callingForm as Form1;
        InitializeComponent();

        pictureBox1.Image = mainForm.MyPictureBoxEnemy.Image;
        pictureBox2.Image = mainForm.MyPictureBoxHero.Image;
        lbl_Health_Value_Enemy.Text = "100";
        lbl_Health_Value_Hero.Text = "100";

    }

    public void attackingPhase()
    {
        Random rnd = new Random();

        int enemy_damage = rnd.Next(1, 25);
        int hero_damage = rnd.Next(2, 15);

        var enemyHealth = Convert.ToInt32(lbl_Health_Value_Enemy);
        var heroHealth = Convert.ToInt32(lbl_Health_Value_Hero);

        if((enemyHealth & heroHealth) > 0)
        {
            enemyHealth = enemyHealth - enemy_damage;
            heroHealth = heroHealth - hero_damage;
        } else
        {
            MessageBox.Show("DEAD");
        }

        lbl_Health_Value_Enemy.Text = enemyHealth.ToString();
        lbl_Health_Value_Hero.Text = heroHealth.ToString();
    }

    private void btnAttack_Click(object sender, EventArgs e)
    {
        attackingPhase();
    }
}
}

错误信息

You need to convert the Text property of a label,

var enemyHealth = Convert.ToInt32(lbl_Health_value_Enemy.Text);
var heroHealth = Convert.ToInt32(lbl_Health_Value_Hero.Text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM