Trying to use a button to divide text inputs. I already have the add/sub/mult done and they work fine just the division does not. Below is my code any help is appreciated. The code seems ok my issue is that the messagebox isn't displaying
private void myDivideButton_Click(object sender, RoutedEventArgs e)
{
int ans = 0;
try
{
ans = int.Parse(myInput1.Text) / int.Parse(myInput2.Text);
MessageBox.Show("The values being divided are " + myInput1.Text + "/" + myInput2.Text + "=" + ans);
}
catch (Exception ex)
{
myInput1.Text = "0";
myInput2.Text = "0";
}
}
}
}
The division of 2 integers is an integer. If you want a double-precision floating point number, you have to cast either of the input to a double or decimal. So, if you want a result with decimals, try this:
double ans = 0;
try
{
ans = double.Parse(myInput1.Text) / double.Parse(myInput2.Text);
MessageBox.Show("The values being divided are " + myInput1.Text + "/" + myInput2.Text + "=" + ans);
}
catch (Exception ex)
{
myInput1.Text = "0";
myInput2.Text = "0";
}
Related
I am trying to make a hex to string converter and for some reason the spacing between bytes in the conversion is multiplied by 2.
I would like it to spit out a single space between characters,
private void button2_Click(object sender, EventArgs e)
{
try
{
textBox1.Clear();
textBox2.Text = textBox2.Text.Replace(" ", "");
string StrValue = "";
while (textBox2.Text.Length > 0)
{
StrValue += System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);
textBox1.Text = textBox1.Text + StrValue + " ";
}
}
catch (Exception ex)
{
MessageBox.Show("Conversion Error Occurred : " + ex.Message, "Conversion Error");
}
}
so "41 41" converted would look like "A A", but this is what happens:
image
Does anybody see what I am doing wrong?
In this line
textBox1.Text = textBox1.Text + StrValue + " ";
you consequently append the result of calculations to your TextBox1.
So, after the first iteration the result is A, you append it and a whitespace to TextBox1.
Then, you take the second 41 and convert it. Now, StrValue is AA and you append it and space to TextBox1, and so on.
You need to move this line out of your while loop:
textBox1.Clear();
textBox2.Text = textBox2.Text.Replace(" ", "");
string StrValue = "";
while (textBox2.Text.Length > 0)
{
StrValue += System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);
}
textBox1.Text = StrValue;
As some people mentioned in comments, you need to stop working with TextBoxes this way. It is pretty confusing. You may want to do the following:
private string HexToString(string hex)
{
string result = "";
while (hex.Length > 0)
{
result += Convert.ToChar(Convert.ToUInt32(hex.Substring(0, 2), 16));
hex = hex.Substring(2); // no need to specify the end
}
return result;
}
Then, in your button click event or wherever else:
textBox1.Text = HexToString(textBox2.Text.Replace(" ", ""));
As simple as that. Or you can even move replacing the whitespaces in the method. Now, this code is readable and is logically separated.
The problem seems to be caused by the accumulated value in StrValue. You should define that variable inside your while, and assign it only (don't append a new value).
while (textBox2.Text.Length > 0)
{
string StrValue = System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);
textBox1.Text = textBox1.Text + StrValue + " ";
}
I am trying to work with if else statements for different things. I need one that pulls the value of a dropdown list to determine what the calculation will be, another that pulls the value of a check box and assigns a calculation, another for input validation for if the number exceeds 32, and the last to give me a value determined by the amount (up to 32) entered into the textbox. I think i've gotten the checkbox statement corrected (guideFee), and the input validation and the one that goes with it seem to be correct already, but I am having trouble assigning the constant decimal values to the dropdown list values and I don't understand why. I have the basetourRate = Convert.ToDecimal(riverTour) and the if statement that follows, but when I run the program I get an error page. I have pasted the whole code. If anyone could help me out i'd greatly appreciate it, thank you!
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butCalculate_Click(object sender, EventArgs e )
{
//1. Declare Variables
decimal totalBaseTourFee;
decimal totalGuideFee;
decimal totalWeekendSurcharge;
decimal subtotal;
decimal salesTaxCharge;
decimal totalCharge;
decimal baseTourRate;
decimal guideFee = 0m;
bool isGuidedTour;
int numberOfRafters;
int numberOfRaftsNeeded;
string riverTour;
string timeOfWeek;
string displayTotalBaseTourFee;
string displayNumberOfRaftsNeeded;
string displayTotalGuideFee;
string displayTotalWeekendSurcharge;
string displaySubtotal;
string displaySalesTaxCharge;
string displayTotalCharge;
const decimal FRENCH_BROAD = 40m;
const decimal NANTAHALA = 30m;
const decimal TUCK = 20m;
const decimal WEEKEND_SURCHARGE = 10M;
const decimal GUIDE_FEE = 35M;
const decimal SALES_TAX_RATE = .07M;
//2. Get Values
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
riverTour = ddlTour.SelectedValue;
isGuidedTour = chkGuided.Checked;
timeOfWeek = rblDay.SelectedValue;
Trace.Warn("numberOfRafters = " + numberOfRafters);
Trace.Warn(("isGuidedTour = " + isGuidedTour));
Trace.Warn("riverTour = " + riverTour);
Trace.Warn("timeOfWeek = " + timeOfWeek);
//Input Validation
if (numberOfRafters > 32)
{
Console.WriteLine("Sorry, we can't handle this large of a group!");
return;
}
//3. Do Calculations
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
if (isGuidedTour == true)
{
guideFee = GUIDE_FEE;
}
else if (!isGuidedTour == false)
{
guideFee = 0;
}
totalBaseTourFee = numberOfRafters * baseTourRate;
numberOfRaftsNeeded = numberOfRafters;
if (numberOfRafters <= 8)
{
numberOfRaftsNeeded = 1;
}
else if (numberOfRafters <= 16)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <= 24)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <=32)
{
numberOfRaftsNeeded = 4;
}
totalGuideFee = numberOfRaftsNeeded * guideFee;
totalWeekendSurcharge = numberOfRafters * WEEKEND_SURCHARGE;
subtotal = totalBaseTourFee + totalGuideFee + totalWeekendSurcharge;
salesTaxCharge = subtotal * SALES_TAX_RATE;
totalCharge = subtotal + salesTaxCharge;
//4. Display Results
displayTotalBaseTourFee = totalBaseTourFee.ToString("C") + "<br>";
displayNumberOfRaftsNeeded = numberOfRaftsNeeded.ToString("C") + "<br>";
displayTotalGuideFee = totalGuideFee.ToString("C") + "<br>";
displayTotalWeekendSurcharge = totalWeekendSurcharge.ToString("C") + "<br>";
displaySubtotal = subtotal.ToString("C") + "<br>";
displaySalesTaxCharge = salesTaxCharge.ToString("C") + "<br>";
displayTotalCharge = totalCharge.ToString("C") + "<br>";
lblTotalBaseTourFee.Text = displayTotalBaseTourFee;
lblNumberOfRafts.Text = displayNumberOfRaftsNeeded;
lblTotalGuideFee.Text = displayTotalGuideFee;
lblTotalWeekendSurcharge.Text = displayTotalWeekendSurcharge;
lblSubtotal.Text = displaySubtotal;
lblSalesTaxCharge.Text = displaySalesTaxCharge;
lblTotalCharge.Text = displayTotalCharge;
}
protected void butClear_Click(object sender, EventArgs e)
{
//Clear TextBox and Label
txtNumberOfRafters.Text = "";
lblTotalBaseTourFee.Text = "";
lblNumberOfRafts.Text = "";
lblTotalGuideFee.Text = "";
lblTotalWeekendSurcharge.Text = "";
lblSubtotal.Text = "";
lblSalesTaxCharge.Text = "";
lblTotalCharge.Text = "";
ddlTour.SelectedIndex = -1;
rblDay.SelectedIndex = -1;
chkGuided.Checked = false;
//Set focus back to name textbox
txtNumberOfRafters.Focus();
}
}
The one thing that sticks out to me is the Convert.ToDecimal(...) call.
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
You are attempting to convert a string to a decimal but then you are comparing that string to a string. My guess is that riverTour is not really a decimal and therefore you are getting an exception. Basically, the logic does not make sense. Convert.ToDecimal will throw an exception if it is not a valid decimal. Therefore, riverTour cannot contain a convertible value to decimal and a comparable value to FB/NH/TK. What exactly are you trying to accomplish? If you are trying to convert to decimal if it is valid and then check those 3 cases if it is not then you should look into decimal.TryParse(string, out decimal) https://msdn.microsoft.com/en-us/library/9zbda557(v=vs.110).aspx. This might help you achieve what you are trying to do.
If the input is always numeric, then you should consider using NumericUpDown. Or, at the very least, use TryParse methods so you can tell if the input is valid or invalid.
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
Is also unsafe.
I am getting an error "Format exception was unhandled." and "Input string was not in a correct format." It is in this line temp_i = float.Parse(textBox3.Text); What is the problem?
//button 2 calculate button
private void button1_Click(object sender, EventArgs e)
{
float temp_e;
float temp_i;
float temp_r;
float temp_p;
//*******************************************************
// Resistance = Volts / Current
//*******************************************************
if (IsNumeric(textBox1.Text) &&
IsNumeric(textBox2.Text) &&
textBox3.Text == (""))
{
temp_e = float.Parse(textBox1.Text); //convert string to number
temp_i = float.Parse(textBox3.Text); //convert string to number
temp_r = temp_e / temp_i; //display 1st result
textBox2.Text = Convert.ToString(temp_r); //post result resistance (R)
//calculate power
temp_p = temp_e * temp_i;
textBox5.Text = Convert.ToString(temp_p);
//display 2nd result
textBox4.Text = Convert.ToString(temp_r) + " * " + Convert.ToString(temp_i) + " = " + Convert.ToString(temp_p) + " watts";
}'
temp_i = float.Parse(textBox3.Text); //convert string to numbe
textBox3.Text certainly contains "" because it was in your if condition.
You can't parse "" to float.
The problem should be obvious; textbox3.Text contains a value which is not valid to be passed to float.Parse. In your case, an empty string (based on the if just above it!
You check whether the textbox is empty and if it is, you're trying to convert to float? Check your logic.
I guess you was trying to do this:
temp_i = float.Parse(textBox2.Text);
Which would make more sense :)
Can any one show me what did i do wrong this code, it produce msg
“Invoke or BeginInvoke cannot be called on a control until the window handle has been created.”
private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == buyColumn.Index)
{
double openprice = (double)dataGridView.Rows[e.RowIndex].Cells[offerColumn.Index].Value;
string symbol = dataGridView.Rows[e.RowIndex].Cells[symbolColumn.Index].Value.ToString();
double quanity= (double)dataGridView.Rows[e.RowIndex].Cells[quanityColumn.Index].Value;
MessageBox.Show("I buy " + symbol + " with " + quanity + " at " + openprice);
}
Update: after debug , these 3 lines cause the issues , plz show me how to fix
double openprice = (double)dataGridView.Rows[e.RowIndex].Cells[offerColumn.Index].Value;
string symbol = dataGridView.Rows[e.RowIndex].Cells[symbolColumn.Index].Value.ToString();
double quanity= (double)dataGridView.Rows[e.RowIndex].Cells[quanityColumn.Index].Value;
Try
if (dataGridView.IsHandleCreated && e.ColumnIndex == buyColumn.Index)
{
double openprice = (double)dataGridView.Rows[e.RowIndex].Cells[offerColumn.Index].Value;
string symbol = dataGridView.Rows[e.RowIndex].Cells[symbolColumn.Index].Value.ToString();
double quanity= (double)dataGridView.Rows[e.RowIndex].Cells[quanityColumn.Index].Value;
MessageBox.Show("I buy " + symbol + " with " + quanity + " at " + openprice);
}
I have the following code in my TextBox leave event:
private void txtAmount_Leave(object sender, EventArgs e)
{
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
But if move back to the previous control by hitting Shift+Tab and again moving back to the same textbox and then trying to move to other the form is getting closed automatically. Why does this happen?
The call to Convert.ToInt32() is probably throwing an exception, likely due to being unable to convert the string in your TextBox to an integer. Convert.ToInt32() can throw the following exceptions (descriptions from MSDN):
FormatException - value does not consist of an optional sign followed by a sequence of digits (0 through 9).
OverflowException - value represents a number that is less than Int32.MinValue or greater than Int32.MaxValue.
It's likely a FormatException, thrown when you leave the TextBox after the $ is prepended to your string, or after you enter any non-numeric characters (letters, etc). To fix this, you have a couple of options:
Add a try / catch block around your code to handle any exceptions.
Use Int32.TryParse() instead of Convert.ToInt32().
Add some code that will prevent non-numeric characters from being entered in your TextBox
Here's an improved version of your event handler:
private void txtAmount_Leave(object sender, EventArgs e)
{
string toParse = txtAmount.Text.TrimStart('$');
int parsed;
if (Int32.TryParse(toParse, out parsed))
{
double res = (double)parsed / 100;
txtAmount.Text = "$" + res.ToString();
}
}
The first time you leave this textbox, its contents will be changed to "$123" (for example). The second time you leave, trying to convert that to int will throw an exception.
You could use the overload of TryParse that takes a NumberStyle, something like this, assuming your goal is to just show a currency value with no decimal places.
double number;
if (double.TryParse(txtAmount.Text, NumberStyles.Currency, CultureInfo.CurrentUICulture, out number))
{
txtAmount.Text = number.ToString("C0");
}
else
{
MessageBox.Show("Could not convert.");
}
After reading #Donut's comment on his answer, I am not sure what your goal is. If you'd like to truncate the cents off but still show the ".00", you can do this:
txtAmount.Text = ((int)number).ToString("C");
Or do this, which will round:
txtAmount.Text = (Convert.ToInt32(number)).ToString("C");
If this does not help, please clarify and let us know what you are trying to accomplish.
Try this:
private void txtAmount_Leave(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtAmount.Text) && txtAmount.Text.StartsWith("$"))
txtAmount.Text = txtAmount.Text.Substring(1);
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
Check the txtAmount.Text for the $ sign, before trying to convert it to an int. If the $ sign is present, strip it out, and convert the rest of the input to an int.
Also, you might want to use the Int32.TryParse method, as that will help you figuring out whether the entered text can be converted into an int or not.
You may want to change your code to remove the $ before working with the number:
private void txtAmount_Leave(object sender, EventArgs e)
{
int x = 0;
int.TryParse(txtAmount.Text.Replace("$", string.Empty), out x);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
I got the solution
private void txtAmount_Leave(object sender, EventArgs e)
{
string strAmnt = string.Empty;
strAmnt = txtAmount.Text;
if (strAmnt.Contains(".") && !strAmnt.Contains("$"))
{
txtAmount.Text = "$" + strAmnt;
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
else
if (strAmnt.Contains("$") && !strAmnt.Contains("."))
{
Int64 amnt = 0;
strAmnt = strAmnt.Replace("$", "");
try
{
amnt = Convert.ToInt64(strAmnt);
double amt = (double)amnt / 100;
txtAmount.Text = "$" + amt.ToString();
}
catch (FormatException ie)
{
MessageBox.Show("Invalid Format");
}
}
else
if (!strAmnt.Contains(".") && !strAmnt.Contains("$"))
{
try
{
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
catch (FormatException ie)
{
MessageBox.Show("InvalidFormat");
}
}
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}