Basically, ive created a form that I can select different shapes that when a value on the track bar is selected, works out both the area and boundary length of either a circle, triangle or square.
The values are currently coming through with a lot of decimal places and I want to set up radio buttons to choose whether 2, 3 or 4 decimal places.
private void sliderBar(object sender, EventArgs e)
{
textBox3.Text = trackBar1.Value.ToString();
if(circleButton.Checked == true)
{
textBox2.Text = (circle.getArea(trackBar1.Value)).ToString();
textBox1.Text = (circle.getBoundLength(trackBar1.Value)).ToString();
}
else if(squareButton.Checked == true)
{
textBox2.Text = (square.getArea(trackBar1.Value)).ToString();
textBox1.Text = (square.getBoundLength(trackBar1.Value)).ToString();
}
else
{
textBox2.Text = (triangle.getArea(trackBar1.Value)).ToString();
textBox1.Text = (triangle.getBoundLength(trackBar1.Value)).ToString();
}
if (decimalPlaces2Button.Checked == true)
{
TextBox2.Text = decimal.Round(textBox2, 2, MidpointRounding.AwayFromZero).ToDouble();
}
}
Here's a working solution which does not Round your number.
static double TakeDecimals(double value, int decimalCount)
{
var truncation = Math.Pow(10, decimalCount);
return Math.Truncate(value * truncation) / truncation;
}
Called like
var input=24.343545;
TakeDecimals(input, 2);//24.34
TakeDecimals(input, 3);//24.343
TakeDecimals(input, 4);//24.3435
UPDATE
In your case, having a string, you can do Convert.ToDouble(yourString) before calling the method.
You can use Math.Round(double, int32)
Math.Round(value, 2);
you can use this:
decimal convertedValue;
decimal.TryParse(textBox2.Text,out convertedValue);
textBox2.Text = Math.Round(convertedValue, 2).ToString();
First convert string to decimal using "Convert.ToDecimal". Then use "Math.Round" to round the decimal number(2, 3 or 4 decimal places).
decimal area;
textBox3.Text = trackBar1.Value.ToString();
if(circleButton.Checked == true)
{
area = circle.getArea(trackBar1.Value)
textBox2.Text = area.ToString();
textBox1.Text = (circle.getBoundLength(trackBar1.Value)).ToString();
}
else if(squareButton.Checked == true)
{
area = square.getArea(trackBar1.Value)
textBox2.Text = area.ToString();
textBox1.Text = (square.getBoundLength(trackBar1.Value)).ToString();
}
else
{
area = triangle.getArea(trackBar1.Value)
textBox2.Text = area.ToString();
textBox1.Text = (triangle.getBoundLength(trackBar1.Value)).ToString();
}
if (decimalPlaces2Button.Checked == true)
{
decimal number1 = Convert.ToDecimal(area);
decimal numWithTwoDecimalPlace = Math.Round(number1, 2);
TextBox2.Text = numWithTwoDecimalPlace.ToString();
}
else if (decimalPlaces3Button.Checked == true)
{
decimal number1 = Convert.ToDecimal(area);
decimal numWithTwoDecimalPlace = Math.Round(number1, 3);
TextBox2.Text = numWithTwoDecimalPlace.ToString();
}
Related
public partial class frmEnhancedInvoiceTotal : Form
{
public frmEnhancedInvoiceTotal()
{
InitializeComponent();
}
private void BtnExit_Click(object sender, EventArgs e)
{
Close();
}
decimal[] decTotalofInvoicesArray = new decimal[5];
int intNumberOfInvoices = 0; //global variables
decimal decTotalOfInvoicesVariable = 0m;
decimal decAverageOfInvoices = 0m;
private void BtnCalculate_Click(object sender, EventArgs e)
{
//Convert = Class, .ToDecimal = method,
//when the user clicks the calulate button,
//we collect the subtotal, determine the appropriate discount,
//calculate the total and output the result to the screen.
//***EARN PARTIAL CREDIT PUT COMMENTS***
//Input
try
{
decimal decSubtotal = 0m; //initialize subtotal with a value of zero. We'll collect from the user later.
if (Decimal.TryParse(txtSubtotal.Text,
System.Globalization.NumberStyles.Currency, //now can type a $ sign and now break the code
System.Globalization.CultureInfo.CurrentCulture,
out decSubtotal)) //.tryparse attempts to convert but is a fail safe
//parse does 2 things - does something and tells you if works
decTotalofInvoicesArray[intNumberOfInvoices] = decSubtotal;
{
//Processing
decimal decDiscountPercent = 0m; //defining a new variable (discount percent) allow for real #, giving it a intial value of 0. Decimal variables you have to add m
if (decSubtotal >= 500m) //if my subtotal is 500 or more
{
decDiscountPercent = 0.2m; //inside braces is what will happen to the question above
//set discount rate to 20%
}
else if (decSubtotal < 500m && decSubtotal >= 250m) //if subtotal is between 250 & 500
//^^redundant because < 500 is already stated in the first if statement
//could just right else if(decSubtotal >=250m)
{
decDiscountPercent = 0.15m; //set discount rate to 15%
}
else if (decSubtotal < 250m && decSubtotal >= 100m) //if subtotal is between 100 and 250
{
decDiscountPercent = 0.1m; //set discount to 10%
}
//if subtotal is less than 100, dicounter percent is 0%
decimal decDiscountAmount = decDiscountPercent * decSubtotal;
decimal decTotal = decSubtotal - decDiscountAmount; //He is going so fast
//Aggregate Processing - across mutliple clicks of the calculate button
//old way of doing it = intNumberOfInvoices = intNumberOfInvoices + 1;
intNumberOfInvoices++; //value of variable plus one
//old way of doing it decTotalOfInvoices = decTotalOfInvoices + decTotal;
decimal decSum = 0m;
for (int intColIndex = 0; intColIndex < decTotalofInvoicesArray.Length; intColIndex++)
{
decSum += decTotalofInvoicesArray[intColIndex];
}
decTotalOfInvoicesVariable = decSum;
decAverageOfInvoices = decSum / decTotalofInvoicesArray.Length;
//Output
txtSubtotal.Text = decSubtotal.ToString("c");
txtDiscountPercent.Text = decDiscountPercent.ToString("p2"); //sending a numeric value and sending it to text = gives error
txtDiscountAmount.Text = decDiscountAmount.ToString("c"); //dot ToString makes value a text value and sends to textbox in form
//c=currency //"p2" - 2 = how many decimal places
//P = percentage
txtTotal.Text = decTotal.ToString("c");
//aggregate output
txtNumberOfInvoices.Text = intNumberOfInvoices.ToString();
txtTotalOfInvoices.Text = decTotalOfInvoicesVariable.ToString("c");
txtAverageOfInvoices.Text = decAverageOfInvoices.ToString("c");
//breakpoint analysis = click on the grey side bar and slowly work through the code to find the error. Essentially pause the code and run the code one point at a time
}
}
catch (FormatException) //you do not know what went wrong in the try part. It just errors anyways because SOMETHING went wrong
{
MessageBox.Show("Please enter valid numeric values.", "Entry Error");
}
catch (OverflowException) //something is to big
{
MessageBox.Show("Please try smaller numbers", "Entry Error");
}
catch //generic error code because why not
{
MessageBox.Show("An unexpected error has occured. Please try again.", "Entry Error");
}
}
private void BtnClearTotals_Click(object sender, EventArgs e)
{
//When resetting aggregate/global info - need to reset the variables AND the visual interface
intNumberOfInvoices = 0;
decTotalOfInvoicesVariable = 0m;
decAverageOfInvoices = 0m;
// txtNumberOfInvoices.Text = ""; //setting the variable to nothing. Erase the information in the text box
txtNumberOfInvoices.Clear();
txtTotalOfInvoices.Clear();
txtAverageOfInvoices.Clear();
}
private void TxtSubtotal_TextChanged(object sender, EventArgs e)
{
txtDiscountPercent.Clear();
txtDiscountAmount.Clear();
txtTotal.Clear();
}
private void BtnDisplayTotals_Click(object sender, EventArgs e)
{
String strOrderTotals = "";
//for (int intColIndex = 0; intColIndex < intNumberOfInvoices; intColIndex++)
//{
// strOrderTotals += decTotalofInvoicesArray[intColIndex] + "\n";
//}
foreach (decimal decTotalInvoices in decTotalofInvoicesArray)
{
if (strOrderTotals == "0")
{
strOrderTotals += decTotalInvoices + "\n";
}
}
MessageBox.Show(strOrderTotals.ToString());
}
private bool IsValidData()
{
return
IsPresent(txtSubtotal) && //did you type anyting
IsDecimal(txtSubtotal) && //make sure you types a real number
IsWithinRange(txtSubtotal, 0m, 1000m); //is the number in the range
}
private bool IsPresent(TextBox textBox) //send an entire textbox into method
{
if (textBox.Text == "")
{
MessageBox.Show(textBox.Tag.ToString() + " is a required field.", "Missing Entry"); //textbox is whatever is in the (TextBox textBox)
textBox.Focus();
return false;
}
return true;
}
private bool IsDecimal(TextBox textBox)
{
decimal decTestValue = 0m;
if (!Decimal.TryParse(textBox.Text, out decTestValue)) //! - dont succusfully tryparse
{
MessageBox.Show(textBox.Tag.ToString() + " must be a numeric value", "Entry Error"); //textbox is whatever is in the (TextBox textBox)
textBox.Focus();
return false;
}
return true;
}
private bool IsInteger(TextBox textBox)
{
int intTestValue = 0;
if (!Int32.TryParse(textBox.Text, out intTestValue)) //! - dont succusfully tryparse
{
MessageBox.Show(textBox.Tag.ToString() + " must be a whole number.", "Missing Entry"); //textbox is whatever is in the (TextBox textBox)
textBox.Focus();
return false;
}
return true;
}
private bool IsWithinRange(TextBox textBox, decimal decMin, decimal decMax)
{
decimal decTestValue = Convert.ToDecimal(textBox.Text);
if (decTestValue < decMin || decTestValue > decMax) //to small or to big
{
MessageBox.Show(textBox.Tag.ToString() + " must be between " + decMin.ToString() + " and " + decMax.ToString() + "." + "Out of Range"); //textbox is whatever is in the (TextBox textBox)
textBox.Focus();
return false;
}
return true;
}
}
}
Basically I have a invoice total windows form were the user inputs a subtotal value and total value is calculated based on the discount percent. In the assignment is says to create an array that hold up to five invoice totals. My problem is when I type lets say 2 subtotal values and click display totals the 2 number I typed in are displayed along with 3 zeros. I am wanting to know how to only display the number I inputted and not the zeros using a foreach loop.
It does not look like you are adding anything in your foreach.
foreach (decimal decTotalInvoices in decTotalofInvoicesArray)
{
if (strOrderTotals == "0")
{
strOrderTotals += decTotalInvoices + "\n";
}
}
MessageBox.Show(strOrderTotals.ToString());
Am I reading this right that you want to have each invoice shown, and do you want the total too? This code with a for loop should work. I
strOrderTotals = "My Invoices\n";
decimal decOrderTotals = 0;
for (int i = 0; i < decTotalofInvoicesArray.Length; i++)
{
if (decTotalofInvoicesArray[i] != 0)
{
strOrderTotals += "Invoice : " + decTotalofInvoicesArray[i] + "\n";
decOrderTotals += decTotalofInvoicesArray[i];
}
}
strOrderTotals += "Total of invoices: " + decOrderTotals;
MessageBox.Show(strOrderTotals.ToString());
I need help with my program in Visual Studio C#. The user must be able to enter a value into the four blank textboxes. The numbers in the textboxes should multiply with their set prices when the user clicks on Calculate. In other words, I want the four textboxes to multiply with their price.
The Form
Here's the calculation code. I managed to get the Children 5-12 textbox to calculate.
private void btnCalculate_Click (object sender, EventArgs e)
{
int FirstTextBoxNumber;
int SecondTextBoxNumber;
int answer;
try
{
Convert.ToInt32(tbSecondNumber.Text);
FirstTextBoxNumber = int.Parse("2");
SecondTextBoxNumber = int.Parse(tbSecondNumber.Text);
answer = FirstTextBoxNumber * SecondTextBoxNumber;
MessageBox.Show("Your total is £" + answer.ToString());
}
catch (FormatException)
{
MessageBox.Show("Please enter a decimal value");
}
}
How the form calculates
Try the following inside your btnCalculate_Click code:
bool isNumeric = true;
double answer = 0;
double firstTextBoxNumber = 0;
double thirdTextBoxNumber = 0;
double fifthTextBoxNumber = 0;
double seventhTextBoxNumber = 0;
int secondTextBoxNumber = 0;
int fourthTextBoxNumber = 0;
int sixTextBoxNumber = 0;
int eightTextBoxNumber = 0;
try
{
if (String.IsNullOrWhiteSpace(tbFirstNumber.Text) || String.IsNullOrWhiteSpace(tbSecondNumber.Text) || String.IsNullOrWhiteSpace(tbThirdNumber.Text) || String.IsNullOrWhiteSpace(tbFourthNumber.Text) || String.IsNullOrWhiteSpace(tbFifthNumber.Text) || String.IsNullOrWhiteSpace(tbSixNumber.Text) || String.IsNullOrWhiteSpace(tbSeventhNumber.Text) || String.IsNullOrWhiteSpace(tbEightNumber.Text))
{
isNumeric = false;
}
else
{
//Check if "Prices" are all Doubles
if (isNumeric)
{
isNumeric = double.TryParse(tbFirstNumber.Text.Replace("£", ""), out firstTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbThirdNumber.Text.Replace("£", ""), out thirdTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbFifthNumber.Text.Replace("£", ""), out fifthTextBoxNumber);
}
if (isNumeric)
{
isNumeric = double.TryParse(tbSeventhNumber.Text.Replace("£", ""), out seventhTextBoxNumber);
}
//Check if "Qty" are all Integers
if (isNumeric)
{
isNumeric = int.TryParse(tbSecondNumber.Text, out secondTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbFourthNumber.Text, out fourthTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbSixNumber.Text, out sixTextBoxNumber);
}
if (isNumeric)
{
isNumeric = int.TryParse(tbEightNumber.Text, out eightTextBoxNumber);
}
}
if (isNumeric)
{
answer = firstTextBoxNumber * secondTextBoxNumber;
answer += thirdTextBoxNumber * fourthTextBoxNumber;
answer += fifthTextBoxNumber * sixTextBoxNumber;
answer += seventhTextBoxNumber * eightTextBoxNumber;
MessageBox.Show("Your total is £" + answer.ToString());
}
else
{
MessageBox.Show("Please enter a decimal value");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The Try Catch block was changed because you should only handle system errors in Try blocks.
Please do note, I made the following assumptions:
The price can change, and can be changed to include cents and fractions of cents.
The price will only remove "£" and no other currency logos.
The Qty will always be an int since you can't have 1.5 children.
You are ok with the system error being shown in a message box to the
user instead of being logged somewhere.
Since this was quick, the code could be expanded on to remove some of the assumptions and to add rounding.
OK. I'm going to try to explain it to you:
You have 8 textboxes in your form.
They all have an identifier like textBox1, textBox2 etc..
What you want to take textBox1 and multiply it by textBox2. And this the same for the other 3 pairs. Then add up the total and display it in a messageBox.
I'll try to send you the right way:
private void btnCalculate_Click (object sender, EventArgs e)
{
int FirstPrice, SecondPrice, ThirdPrice, FourthPrice;
int FirstQnty, SecondQnty, ThirdQnty, FourthQnty;
int answer = 0;
try
{
FirstPrice = (int)TextBox1.Text.Replace("£", "");
SecondPrice = (int)TextBox2.Text;
ThirdPrice = (int)TextBox3.Text.Replace("£", "");
FourthPrice = (int)TextBox4.Text;
FirstQty = (int)TextBox5.Text.Replace("£", "");
SecondQty = (int)TextBox6.Text;
ThirdQty = (int)TextBox7.Text.Replace("£", "");
FourthQty = (int)TextBox8.Text;
answer = FirstPrice * FirstQty;
answer += SecondPrice * SecondQty;
answer += ThirdPrice * ThirdQty;
answer += FourthPrice * FourthQty;
MessageBox.Show("Your total is £" + answer.ToString());
}
catch (FormatException)
{
MessageBox.Show("Please enter a decimal value");
}
}
It might contain some spelling errors, but it should work.
Just replace the TextBox identifiers to the ones in your form.
I am trying to do 1 of 3 options when selecting from 2 different listboxes with the same measurement words.
The user enters a number into a textbox, then selects one of 3 units in the FromList listbox (the units are Inches, Feet, and Yards), then selects one of 3 units in the ToList listbox (the units in this are also Inches, Feet, and Yards).
When the calculate button is clicked it will either convert the measurement inches to inches (Do no math and just spit out what they entered to the label) or inches to feet or inches to yards if the FromList has Inches selected, and display the output to a label. It would also do feet to inches, feet to feet(do no math), and feet to yards. Lastly, it would do yards to inches, yards to feet, and yards to yards (do no math).
Both listboxes have SelectionMode set to One so user can only pick 1 item from each listbox. I can set the first listbox to a value with SelectedItem, but the 9 errors in the code it is highlighting is if I try to set it if an item in the 2nd listbox is selected. Here's what I've tried so far:
public frmConverter()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtEntered.Text = "";
lblOutput.Text = "";
}
private void btnCalc_Click(object sender, EventArgs e)
{
string Fromlist;
string ToList;
double Entered, Output;
Entered = Convert.ToDouble(txtEntered.Text);
if (FromList == "Inches" && ToList == "Inches")
{
lblOutput.Text = txtEntered.Text + " Inches";
}
else if (FromList == "Inches" && ToList =="Feet")
{
Output = Entered / 12;
lblOutput.Text = Output.ToString("N2") + (" Feet");
}
else if (FromList == "Inches" && ToList == "Yards")
{
Output = Entered / 36;
lblOutput.Text = Output.ToString("N2") + (" Yards");
}
else if (FromList == "Feet" && ToList == "Inches")
{
Output = Entered * 12;
lblOutput.Text = Output.ToString("N2") + (" Inches");
}
else if (FromList == "Feet" && ToList == "Feet")
{
lblOutput.Text = txtEntered.Text + " Feet";
}
else if (FromList == "Feet" && ToList == "Yards")
{
Output = Entered / 3;
lblOutput.Text = Output.ToString("N2") + (" Yards");
}
else if (FromList == "Yards" && ToList == "Inches")
{
Output = Entered * 36;
lblOutput.Text = Output.ToString("N2") + (" Inches");
}
else if (FromList == "Yards" && ToList == "Feet")
{
Output = Entered * 12;
lblOutput.Text = Output.ToString("N2") + (" Feet");
}
else if (FromList == "Yards" && ToList == "Yards")
{
lblOutput.Text = txtEntered + " Yards";
}
}
}
One of your problems is you're using the assignment operator,=, instead of the equality operator,==, in your if statements.
if (FromList.SelectedItem.ToString() == "Inches" && ToList.SelectedItem.ToString() == "Inches")
{
lblOutput.Text = txtEntered.Text + " Inches";
}
Also Entered is never given a value.
Something you might want to consider, is using an enum to simplify your code and get rid of all those if statements:
enum Conversions
{
Inches = 1,
Feet = 12,
Yards = 36,
}
double DoConversion(string from, string to, double quantity)
{
Conversions convertFrom = Conversions.Inches;
Conversions convertTo = Conversions.Inches;
if (Enum.TryParse<Conversions>(from, out convertFrom) && Enum.TryParse<Conversions>(to, out convertTo))
{
return quantity * ((double)convertFrom / (double)convertTo);
}
else
{
return 0;
}
}
This function takes the From/To units as strings and a double for the quantity and does the conversion. Instead of different algorithms for multiplying or dividing, it just multiplies by the division of the 2 conversion values
The issue is you have taken FromList and ToList as string and you are trying to polulate SelectedItem propert from FromList/ToList but there is no such property exists in FromList/ToList as you have taken them as string in your code. May be you required to use your Listcontrols defined in desigining rather than taking string objects in code.
private void btnCalc_Click(object sender, EventArgs e)
{
string Fromlist; // this is string so will not work for you
string ToList; // this is string so will not work for you
string Inches;
string Feet;
string Yards;
double Entered, Output;
//as FromList and ToList are string defined above below logic will not work as there is no property like SelectedItem in string.
if (FromList.SelectedItem = "Inches" && ToList.SelectedItem = "Inches")
{
}
Ok, so I recoded it using switch and parse and it works as intended now. Thanks for everyone's help!Here is the working code :
public Form1()
{
InitializeComponent();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtEntered.Text = "";
lblOutput.Text = "";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnCalc_Click(object sender, EventArgs e)
{
string From;
string To;
double Entered, Output;
Entered = double.Parse(txtEntered.Text);
if (FromList.SelectedIndex != -1)
{
From = FromList.SelectedItem.ToString();
To = ToList.SelectedItem.ToString();
switch (From)
{
case "Inches":
switch (To)
{
case "Inches":
Output = Entered;
lblOutput.Text = Output.ToString("N2") + " Inches";
break;
case "Feet":
Output = Entered / 12;
lblOutput.Text = Output.ToString("N2") + " Feet";
break;
case "Yards":
Output = Entered / 36;
lblOutput.Text = Output.ToString("N2") + " Yards";
break;
}
break;
case "Feet":
switch (To)
{
case "Inches":
Output = Entered * 12;
lblOutput.Text = Output.ToString("N2") + " Inches";
break;
case "Feet":
Output = Entered;
lblOutput.Text = Output.ToString("N2") + " Feet";
break;
case "Yards":
Output = Entered / 3;
lblOutput.Text = Output.ToString("N2") + " Yards";
break;
}
break;
case "Yards":
switch (To)
{
case "Inches":
Output = Entered * 36;
lblOutput.Text = Output.ToString("N2") + " Inches";
break;
case "Feet":
Output = Entered * 3;
lblOutput.Text = Output.ToString("N2") + " Feet";
break;
case "Yards":
Output = Entered;
lblOutput.Text = Output.ToString("N2") + " Yards";
break;
}
break;
}
}
}
}
}
I have a datagrid view which is editable. I'm getting the value of a cell and then calculate the value of another cell. To do this I have handled CellEndEdit and CellBeginEdit events.
quantity = 0, quantity1 = 0, quantity_wt1 = 0, quantity_wt = 0, ekundag = 0;
private void grdCaret_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
quantity = val;
ekundag = ekundag + quantity;
tbTotDag_cr.Text = ekundag.ToString();
}
if (e.ColumnIndex == 2)
{
float val = float.Parse(value);
total = val;
ekunrakam = ekunrakam + total;
tbTotPrice_cr.Text = ekunrakam.ToString();
}
grdCaret.Columns[3].ReadOnly = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void grdCaret_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
rate = 0;
quantity1 = quantity;
total1 = total;
rate = (total1 / quantity1);
if (e.ColumnIndex == 3)
{
grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = rate.ToString();
grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = true;
// quantity = 0;
// total = 0;
}
}
In the grid I have columns as quantity, total and rate. I get the above error here:
if (e.ColumnIndex == 1)
{
int val = int.Parse(value);
quantity = val;
ekundag = ekundag + quantity;
tbTotDag_cr.Text = ekundag.ToString();
}
When I enter quantity and click on the total column in gridview. Please help me fix this
AFAIK the int.Parse() function can possibly cause this kind of exceptions.
Have you tried to check the value in the cell? Isn't it possible, that some other characters are in the cell, not only the numbers? White spaces for example.
The value you have entered into your Cell can't be parsed as Integer, so it will fail #
int val = int.Parse(value);
Your input string 'value' is not in a valid format to be parsed to an integer. Take a look at this: http://www.codeproject.com/Articles/32885/Difference-Between-Int32-Parse-Convert-ToInt32-and
try using Text instead of ToString()
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.Text;
in place of
string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
I have a numeric value in a Textbox that I'd like to format as a percent. How can I do this in C# or VB.NET?
In VB.NET...
YourTextbox.Text = temp.ToString("0%")
And C#...
YourTextbox.Text = temp.ToString("0%");
Building on Larsenal's answer, how about using the TextBox.Validating event something like this:
yourTextBox_Validating(object sender, CancelEventArgs e)
{
double doubleValue;
if(Double.TryParse(yourTextBox.Text, out doubleValue))
{
yourTextBox.Text = doubleValue.ToString("0%");
}
else
{
e.Cancel = true;
// do some sort of error reporting
}
}
For added fun, let's make the parser a bit more sophisticated.
Instead of Double.TryParse, let's create Percent.TryParse which passes these tests:
100.0 == " 100.0 "
55.0 == " 55% "
100.0 == "1"
1.0 == " 1 % "
0.9 == " 0.9 % "
90 == " 0.9 "
50.0 == "50 "
1.001 == " 1.001"
I think those rules look fair if I was a user required to enter a percent. It allows you to enter decimal values along with percents (requiring the "%" end char or that the value entered is greater than 1).
public static class Percent {
static string LOCAL_PERCENT = "%";
static Regex PARSE_RE = new Regex(#"([\d\.,]+)\s*("+LOCAL_PERCENT+")?");
public static bool TryParse(string str, out double ret) {
var m = PARSE_RE.Match(str);
if (m.Success) {
double val;
if (!double.TryParse(m.Groups[1].Value, out val)) {
ret = 0.0;
return false;
}
bool perc = (m.Groups[2].Value == LOCAL_PERCENT);
perc = perc || (!perc && val > 1.0);
ret = perc ? val : val * 100.0;
return true;
}
else {
ret = 0.0;
return false;
}
}
public static double Parse(string str) {
double ret;
if (!TryParse(str, out ret)) {
throw new FormatException("Cannot parse: " + str);
}
return ret;
}
public static double ParsePercent(this string str) {
return Parse(str);
}
}
Of course, this is all overkill if you simply put the "%" sign outside of the TextBox.
A little trickery for populating Label's (& TexBox) in a panel before users input. This covers decimal, integers, percent, and strings.
Using C# 1.1 in the Page_Load event before any thing happens:
if (!this.IsPostBack)
{
pnlIntake.Visible = true // what our guest will see & then disappear
pnlResult.Visible = false // what will show up when the 'Submit' button fires
txtIperson.Text = "enter who";
lbl1R.Text = String.Format(Convert.ToString(0)); // how many times
lbl2R.Text = String.Format(Convert.ToString(365)); // days a year
lblPercentTime = String.Format("{0:p}", 0.00); // or one zero will work '0'
lblDecimal = String.Format("{0:d}", 0.00); // to use as multiplier
lblMoney = String.Format("{0:c}", 0.00); // I just like money
// < some code goes here - if you want
}