So there are still some logic errors in this that I am working on. I'm not worried about those, and I want to figure them out myself.
I'm working on a slot machine app for some independent study and when I try to parse the value of the label that shows the players cash into a variable I am getting a format exception. How do fix this and more importantly why am I getting this exception?
I have also tried using TryParse and Convert.ToDouble.
protected void PullBTN_Click(object sender, EventArgs e)
{
// Get players cash//////////////////////////////
double playersCash = Convert.ToDouble(playerMoneyLBL.Text);
// Other way I tried that didn't work ////////////
//double playersCash = 0;
//double.TryParse(playerMoneyLBL.Text.Trim(), out playersCash);
// Get players bet /////////////////////////////
double playerBet = 0;
if (!double.TryParse(betTB.Text, out playerBet))
return;
// Spin the slots//////////////////////////////
Image1.ImageUrl = spinReel();
Image2.ImageUrl = spinReel();
Image3.ImageUrl = spinReel();
// Find multiplier //////////////////////////////
double multiplier = findMultiplier();
// Find winnings ///////////////////////////////
double winnnings = multiplier * playerBet;
playerMoneyLBL.Text = (playersCash + winnnings).ToString();
// Add winnings to players money //////////////
playerMoneyLBL.Text = (playersCash + winnnings).ToString();
}
Your problem is here.
playerMoneyLBL.Text = "$100";
As you have $ in-front of 100, you cannot convert that to float. Make it something like this.
double playersCash = Convert.ToDouble(playerMoneyLBL.Text.substring(1));
double.Parse uses your CurrentCulture settings on the current environment by default.
double d = double.Parse("Your Text Here", CultureInfo.InvariantCulture);
Or if you want it more secure way, try:
value = "Your String";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol| NumberStyles.AllowThousands;
culture = CultureInfo.InvariantCulture
if (Double.TryParse(value, style, culture, out number))
{
// Write your code for true condition
}
else
{
// Write your code for false condition
}
Related
ok I am running into a problem. I have a decimal in a textbox that I am trying to Range between a set number. As you can see in the picture I have a value that is in the Full Scale, which updates the value on the CalCert with the decimal 2.9995 mV/V.
The issue here is the decimal value has to be plus/minus 30 of 3 mV. example. 2.9970 - 3.0030 that is the range. Anything outside the range I am needing it to trigger a warning dialog. My code that I was going to use I am not sure why its not working.
I am using if statements but the only error is in the ("3.0031") section.
double value = 0;
if (double.TryParse(TxtFullScale.Text, out value))
{
value /= 10000;
}
TxtCalFullScale.Text = string.Format("{0:#.0000}", value) + " " + "mV/V";
if (TxtFullScale.Text >= TxtFullScale.Text.ToString("3.0031"))
{
MessageBox.Show("Full Scale value is in a non conformence state.");
}
else if (TxtFullScale.Text <= TxtFullScale.Text.ToString("2.9970"))
{
MessageBox.Show("Full Scale value is in a non conformence state.");
}
I can take and make the code work with to a point with
if (TxtFullScale.Text == "3.0031")
{
MessageBox.Show("Full Scale value is in a non conformence state.");
}
else if (TxtFullScale.Text =="2.9970")
{
MessageBox.Show("Full Scale value is in a non conformence state.");
}
However if the range is put in the text as 3.0032 then it never shows the messagebox. What am I missing here?
So, first, you can't do math operations with strings on C#
var a = "3";
var b = "2";
Console.WriteLine(a+b);
Will result in 32!
Second, this line is a bit strange
TxtFullScale.Text >= TxtFullScale.Text.ToString("3.0031")
Should be like
TxtFullScale.Text >= "3.0031"
you need to parse the number as an decimal, then compare, like this:
public const double LIMIT_1 = 3.0031;
public static void Main()
{
var val = "3.0032";
var x = double.TryParse(val, out double dec);
if(dec >= LIMIT_1)
Console.WriteLine("yay");
}
This is my first post. So..critique is always welcomed.
My question is straight forward just by looking at the title.
How can I use a loop to insert values to different labels by using their reference (get,set methods are in a different form)
What I've tried is to create an array with the references of the labels. The thing is.. it assigns the new values to the array rather than changing the reference which will change the label.
I find it a bit difficult to explain it further than that.
If you have any questions, I will try to answer them best to my knowledge
private void button1_Click(object sender, EventArgs e)
{
int numOfPeriods = Convert.ToInt32(cmbPeriods.Text)-1;
string initialString = cmbStartTime.Text; //Gets the input from combo box "cmbStartTime".
string newTime;
decimal dec = Convert.ToDecimal(TimeSpan.Parse(initialString).TotalHours); //Converts the set by user Lesson start time to a decimal value.
decimal dec2;
decimal lessonLength = 1; // Default lesson length is set to 1 hour.
TimeSpan time;
Test FormOpen = new Test();
string[] periodStartTimes = new string[9] //Loop referencing the labels on Form TEST
{
FormOpen.startTime,FormOpen.startTime2, FormOpen.startTime3, FormOpen.startTime4,
FormOpen.startTime5, FormOpen.startTime6, FormOpen.startTime7, FormOpen.startTime8,
FormOpen.startTime9
};
if (cmbLessonLength.Text != "") //If the combo box "cmbLessonLength" is not empty, use that value instead of the default lesson lenght.
{
lessonLength = Convert.ToDecimal(cmbLessonLength.Text)/60; //Converts minutes to hours.
}
dec2 = dec + lessonLength;
time = TimeSpan.FromHours(Double.Parse(dec2.ToString()));
newTime = time.ToString();
if (newTime[0] == '0')
{
FormOpen.startTime = initialString + " - " + newTime.Remove(5).Remove(0, 1);
}
else
{
FormOpen.startTime = initialString + " - " + newTime.Remove(5);
}
for (int x = 1; x <= numOfPeriods; x++) //LOOP THAT ASSIGNS VALUES TO THE ARRAY AND NOT THE REFERENCE INSIDE IT
{
decimal workingNumber = lessonLength*x;
decimal Convert0 = dec + workingNumber;
TimeSpan Convert1 = TimeSpan.FromHours(Double.Parse(Convert0.ToString()));
string Convert2 = Convert1.ToString().Remove(5);
periodStartTimes[x] = Convert2;
}
FormOpen.subjectName = cmbSubjects.Text;
FormOpen.startTime2 = periodStartTimes[1]; //IT DOES WORK LIKE THIS
FormOpen.startTime3 = periodStartTimes[2];
FormOpen.ShowDialog();
}
I have provided the whole code, so it's clearer and if there's a more efficient way of coding this I would be really thankful if someone could give me a few tips.
Your code cannot work using that array periodStartTimes This is an array of strings and when you initialize it you get the value of the property (IE the current text of the labels) not a reference to a property that you can use to change the labels.
In any case it is a bad practice to allow a different class instance change the internal values of another class. It is better to provide a public method used by the external classes to change the internal properties.
So for example your Test form class could have a public method named as SetTextLabel
public class Test : Form
{
....
public void SetLabelText(string name, string value)
{
switch(name)
{
case "startTime":
this.labelForStartTime.Text = value;
break;
case "label1":
this.firstLabelToUpdate.Text = value;
break;
...
// and so on for all other labels
}
}
}
In this way the code that changes the label is inside the Test class and you can add all the checks and validations required with full access to all the internal variables of the Test class.
Now your loop can be rewritten as
for (int x = 1; x <= numOfPeriods; x++)
{
decimal workingNumber = lessonLength*x;
decimal Convert0 = dec + workingNumber;
TimeSpan Convert1 = TimeSpan.FromHours(Double.Parse(Convert0.ToString()));
string Convert2 = Convert1.ToString().Remove(5);
FormOpen.SetLabelText("label" + x.ToString, Convert2;
}
Of course now you don't need anymore the array, and this will probably remove another error present in your actual code. The array is fixed at 9 elements but you loop for numOfPeriods starting from 1 (thus skipping the first element) and if numOfPeriods is bigger than 8 your code will crash with IndexOutOfRange exception
I have:
textbox1.text == 1.4087
textbox2.text == 521.54
It's not hardcoded, I get it from JSON. Anyway, I want to multiply these two numbers.
I use this code:
double curr = 0.0;
double price = 0.0;
double multiply = 0.0;
double.TryParse(textBox1.Text, out curr);
double.TryParse(textBox2.Text, out price);
multiply = curr * price;
textBox3.Text = multiply.ToString();
I also tried with Convert.ToDouble still no luck.
I always get 0 in textBox3. Apparently the strings are not recognized as double. But they are. Any ideas? Thanks!
EDIT: From JSON:
{"high": "567.88", "last": "543.95", "timestamp": "1394987785",
I'm using this code to get what i need:
Regex expression = new Regex(#"last"":\s""(?<Identifier>[0-9]+\.[0-9]+)");
var results = expression.Matches(Cryp);
foreach (Match match in results)
{
textBox1.Text = match.Groups["Identifier"].Value;
}
Any issues here?
Try This:
double.TryParse(textBox1,NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out curr);
double.TryParse(textBox2.Text,NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out price);
multiply = curr * price;
I would assume one of the TryParse calls fails resulting in it keeping a value of 0 so regardless of what the working one is, you're going to get 0 for a result.
I just wrote up a basic ASP.NET application with three textboxes and then just pasted your code without changing anything into the event handler for a submit button. Manually typing the two numbers you provided gave the correct answer of 734.693398 in TextBox3. Your inputs must be off.
protected void btnView_Click(object sender, EventArgs e)
{
int StudentAdmissionNo = Convert.ToInt32(txtAdmissionNo.Text);
string StudentName = txtStudentName.Text;
DateTime DateOfBirth = Convert.ToDateTime(txtDOB.Text);
string Gender = txtGender.Text;
string Standard = txtstandard.Text;
string Section = txtSection.Text;
int Telugu = Convert.ToInt32(txtTelugu.Text);
int English = Convert.ToInt32(txtEnglish.Text);
int Mathematics = Convert.ToInt32(txtMathematics.Text);
//int Total = Convert.ToInt32(lblTot.Text);
//double Average = Convert.ToDouble(lblAve.Text);
string Result = lblRes.Text;
lblTot.Text = (txtTelugu.Text + txtEnglish.Text + txtMathematics.Text); # Total in coming if i enter the 45 65 65 = its coming 456565 like i did wrong?
lblAve.Text = ((lblTot.Text) / 3.00); //This also gives an error
}
In this code I have an error coming from lblTot = to add marks and it coming like same to printing that numbers what I entered and average also not working.
You are concatenating the Text. When you use + with text/string it acts as a concatenation operator.
You need to convert text to Integer for arithmatic operations first.
Use Convert.ToInt32(input);
Replacing your code with the below lines should fix it.
lblTot.Text = (Convert.ToInt32(txtTelugu.Text) + Convert.ToInt32(txtEnglish.Text) + Convert.ToInt32(txtMathematics.Text)).ToString();
lblAve.Text = ((Convert.ToInt32(lblTot.Text)) / 3.00).ToString();
Update
I just noticed that you have already assigned the required values to integers here:
int Telugu = Convert.ToInt32(txtTelugu.Text);
int English = Convert.ToInt32(txtEnglish.Text);
int Mathematics = Convert.ToInt32(txtMathematics.Text);
Which is correct, you just needed to add these variables, like:
int total = Telugu + English + Mathematics;
lblTot.Text = total.ToString();
And then, for average just use the total variable that we just assigned the value to:
lblAve.Text = Convert.ToString(Convert.ToDouble(total / 3.00)); // convert the average to double as you may get values with decimal point. And then convert it back to string in order to assign it to a Label control.
If my assumption of what you're trying to do is correct your code should look like this.
decimal total = Teluga + English + Mathematics;
decimal average = (Teluga + English + Mathematics) / 3.00;
lblTot.Text = total.ToString();
lblAve.Text = average.ToString();
You are trying to use strings to perform mathematical operations and that won't work.
Also, typically
int x = Int32.TryParse(txtEnglish.Text)
is a better way to turn string into integers
The root of both your problems is that a textbox.Text property is a string.
In your first problem, you are concatenating strings, which is why it's giving you you 456565.
In your second problem, you are trying to perform arithmetic on a string and a number.
Cast your strings as numbers by declaring an Int32 variable placeholder and using the TryParse method on your string, like so:
Int32 txtTeluguResult;
Int32.TryParse(txtTelugu.Text, txtTeluguResult);
Also note that TryParse will put 0 in for your result variable if it cannot successfully parse the text input. You may wish to use Convert.ToInt32() instead, which throws a FormatException if it fails, depending on what behavior you want.
lblTot.Text = (txtTelugu.Text + txtEnglish.Text + txtMathematics.Text); # Total in coming if i enter the 45 65 65 = its coming 456565 like i did wrong?
lblAve.Text = ((lblTot.Text) / 3.00); this also giving error?
you are using string variables not int or real or decimal
do something like
lblTot.Text = (((int)txtTelugu.Text + (int)txtEnglish.Text + (int)txtMathematics.Text)).ToString();
lblAve.Text = (((int)(lblTot.Text) / 3.00)).ToString(); this also giving error?
how to make a text box to accept only decimal value with precision.
example.if the text box value is 12 .how to convert it to 12.00
and if it is 12.00 it must remain same..
thanks in advance.
You want to use a NumericUpDown-Control.
Edit: But to answer your question. To make TextBox-Control only accept numeric values, you'd have to suppress every key you do not want, and after that convert the input into a Decimal.
Decimal value = Convert.ToDecimal(this.yourTextBox.Text);
Or the fail-safe way:
Decimal value = 0;
String toParse = this.yourTextBox.Text;
if(!Decimal.TryParse(toParse, out value) {
// The user managed to break it...
}
A simple, fixed width variant is:
textBox1.Text = String.Format("{0,12:0.00}", textBox1.Text);
0 = first value (in this case
textBox1.Text)
12 = minimal width
0.00 = decimal (i.e. you could use #) find out more variants with
String.Format on msdn
Add an Event to the TextBoxChanged:
public void On_textbox1TextChanged(object sender, EventArgs e)
{
Double dblVal = 0;
if(Double.TryParse(this.textbox1.Text, ref dblVal))
{
this.textbox1.Text = dblVal.ToString("N2"); // Prints two 2 decimal places
}
else { /* Handle invalid value */ }
}
I would do a combination of the above on text change, and string formatting, but also go with a MASKED textbox. That will allow you to put in an expected mask to allow too.