C# label string to int conversion error - c#

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);

Related

Error creating a line graph on winform

I keep getting this error when trying to initialise the form with my graph on it. Can't figure out a work around for it. Think it has something to do with Data Binding
Any ideas ?
Here is my code -
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;
using System.Windows.Forms.DataVisualization.Charting;
namespace NoCAnalysisTool2
{
public partial class Visualisation : UserControl
{
public string tx_graph { get; set; }
public List<int> tx_graphData { get; set; }
public Visualisation(string txGraph, List<int> tx_GData)
{
InitializeComponent();
tx_graph = txGraph;
tx_graphData = tx_GData;
// Set 3D chart settings
chart1.ChartAreas["Default"].Area3DStyle.Enable3D = true;
chart1.ChartAreas["Default"].Area3DStyle.IsRightAngleAxes = false;
chart1.ChartAreas["Default"].Area3DStyle.Inclination = 40;
chart1.ChartAreas["Default"].Area3DStyle.Rotation = 20;
chart1.ChartAreas["Default"].Area3DStyle.LightStyle = LightStyle.Realistic;
// Populate series with random data
Random random = new Random();
for (int pointIndex = 0; pointIndex < 10; pointIndex++)
{
chart1.Series["Series1"].Points.AddY(random.Next(45, 95));
chart1.Series["Series2"].Points.AddY(random.Next(5, 75));
}
// Set series chart type
chart1.Series["Series1"].ChartType = SeriesChartType.Line;
chart1.Series["Series2"].ChartType = SeriesChartType.Spline;
// Set point labels
chart1.Series["Series1"].IsValueShownAsLabel = true;
chart1.Series["Series2"].IsValueShownAsLabel = true;
// Enable X axis margin
chart1.ChartAreas["Default"].AxisX.IsMarginVisible = true;
// Enable the ShowMarkerLines
chart1.Series["Series1"]["ShowMarkerLines"] = "true";
chart1.Series["Series2"]["ShowMarkerLines"] = "true";
}
private void TxGraph_Load(object sender, EventArgs e)
{
}
private void Tx_graph_Click(object sender, EventArgs e)
{
}
private void Visualisation_Load(object sender, EventArgs e)
{
}
private void chart11_Click(object sender, EventArgs e)
{
}
}
}
The 'default' ChartArea is not called "Default" but "ChartArea1".
Trying to access an indexer by a wrong name results in an Argument Exeption.
You have the choice of either calling it by its index:
ChartArea ca = chart1.ChartAreas[0];
Or by its right name:
ChartArea ca = chart1.ChartAreas["ChartArea1"];
Or set the Name property th a string you like..:
chart1.ChartAreas[0].Name = "Default";
..and then calli it by that Name:
chart1.ChartAreas["Default"].Area3DStyle.Enable3D = true;
Btw: I hope you have added the 2nd Series in the designer and given it the right Name ;-)

Why textBox in WinForms cant display double?

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 P2_7_24_2016_ED_app
{
public partial class Form1 : Form
{
int win;
int loss;
int winCounter;
int lossCounter;
public Form1()
{
InitializeComponent();
}
private void buttonWin_Click(object sender, EventArgs e)
{
this.textBoxWin.Text = "";
++win;
++winCounter;
this.textBoxWin.Text = win.ToString();
}
private void buttonLoss_Click(object sender, EventArgs e)
{
this.textBoxLoss.Text = "";
++loss;
++lossCounter;
this.textBoxLoss.Text = loss.ToString();
}
private void buttonRate_Click(object sender, EventArgs e)
{
textBox1.Text = "";
double result = winCounter / (winCounter + lossCounter);
textBox1.Text = result.ToString();
}
}
}
This is the code in windows form application, its short so i'm not going to explain everything.
Problem is that in the end textBox1.Text = result.ToString();
is showing "0", but it should be some numbers. When the win winCounter is like 1, and lossCounter is 1 it should insert 1/(1+1) = 0.5 but it says "0". I tried everything i knew so please give me a tip.
This is integer arithmetic:
(winCounter/(winCounter+lossCounter))
The result is not going to be what you expect.
Cast either winCounter or (winCounter+lossCounter) to a floating point type (float, double or decimal depending on the speed/accuracy you need) before doing the division:
(winCounter/(decimal)(winCounter+lossCounter))
or
((double)winCounter/(winCounter+lossCounter))
and you'll get the result you expect.
As described in the comments, you will need to cast your result. This should work:
textBox1.Text = (winCounter/(double)(winCounter+lossCounter)).ToString();

Hospital Stay: I cannot find a reason why my CalcTotalChargs is not being recognized

This SHOULD work because, despite being declared as the last private double, the modularization of C# should allow the first CalcTotalChargs be recognized as well. This is preventing me from running the program successfully
Here is the code I have so far:
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 Adam_Zeidan_HW7CH6_6_Hospital_Stay
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calculateButton_Click(object sender, EventArgs e)
{
*label6.Text = "You will be paying: " + **CalcTotalChargs()**.ToString("c");*
}
private int CalcStayCharges()
{
return (350 * int.Parse(textBox1.Text)); // Calculating the amount of days by $350
}
private double CalcMiscCharges()
{
return double.Parse(textBox2.Text) + double.Parse(textBox3.Text) +
double.Parse(textBox5.Text) + double.Parse(textBox5.Text); // Adding together the other values entered within the textboxes to add to the eventual total charge
}
private double CalcTotalCharges()
{
return CalcMiscCharges() + CalcStayCharges(); // Adding the number value of the sum of the previous calculation to the sum of the 350 * Number of days staying
}
}
}
Your function spelt incorrectly, as such it couldn't complete.
CalcTotalChargs().ToString("c") should be CalcTotalCharges().ToString("c")
Use the code below and the issue should be resolved.
private void calculateButton_Click(object sender, EventArgs e)
{
label6.Text = "You will be paying: " + CalcTotalCharges().ToString("c");
}

How can I send Numpad Keys through my program

I'm just trying to create a program that presses Numpad 0 in the program, every few set seconds. This is what I have so far.
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
int enabled = 0;
public Form1()
{
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
if (enabled == 0)
{
Start.Text = "Stop";
Timer.Enabled = true;
enabled = 1;
}
else
{
Start.Text = "Start";
Timer.Enabled = false;
enabled = 0;
label2.Text = "0";
}
}
private void Timer_Tick(object sender, EventArgs e)
{
SendKeys.Send("{NumpadIns}");
label2.Text = Convert.ToString(Convert.ToInt32(label2.Text) + 1);
}
}
}
I have tried this so far
{NumpadIns}
{NumIns}
{Num0}
{INS}
Nothing seems to work, the program I'm using with it is bound to Num Zero so it has to be Num Zero and not 0 on the top row, or Insert. Thanks (Yes I have googled but for some reason this is really hard to find).
From my experience, you should you some wrappers like Input Simulator. It is easy to use and have many pre-defined enums so you do not need to pass String argument.

SoundPlayer and MemoryStream in C#

I build a sample program that select a wav file, then you can play the selected file with 2x speed Or 4x speed
the code of the previous app is :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace PlayWave
{
public partial class Form1 : Form
{
private byte[] B;
private OpenFileDialog open;
public Form1()
{
open = new OpenFileDialog();
open.Filter = "Wav Sound File (*.Wav)|*.wav";
InitializeComponent();
}
private void SelectFile_Click(object sender, EventArgs e)
{
if (!(open.ShowDialog() == DialogResult.OK))
{
return;
}
}
private void twoX_Click(object sender, EventArgs e)
{
B = File.ReadAllBytes(open.FileName);
int samplerate = BitConverter.ToInt32(B, 24) * 2;
Array.Copy(BitConverter.GetBytes(samplerate), 0, B, 24, 4);
using (System.Media.SoundPlayer SP = new System.Media.SoundPlayer(new MemoryStream(B)))
{
SP.Play();
}
}
private void fourX_Click(object sender, EventArgs e)
{
B = File.ReadAllBytes(open.FileName);
int samplerate = BitConverter.ToInt32(B, 24) * 4;
Array.Copy(BitConverter.GetBytes(samplerate), 0, B, 24, 4);
using (System.Media.SoundPlayer SP = new System.Media.SoundPlayer(new MemoryStream(B)))
{
SP.Play();
}
}
}
}
above, I changed the value of (25,26,27,28) bytes of file which represent the sample rate of wave file then save the changes and play the file using System.Media.SoundPlayer and MemoryStream .
my problem is that when I clicked on the button the plays the file in 2x speed over 3 clicks , my program stop and error message appaer ,
can any one tell me why ?

Categories

Resources