change decimal place in textbox using numericUpDown - c#

Im using Visual Studio 2010, windows form (c#).
I need change decimals place of value in textbox using numericUpDown1.
example:
I tryed this code:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
// tbxConvertito.Text = (decimal.Parse(tbxConvertito.Text) * 10m).ToString();
if (numericUpDown1.Value == 0)
{
int decimalPlace = 0;
// Decimal xDecimal = decimal.Parse(tbxConvertito.text);
decimal xDecimal = decimal.Parse(tbxConvertito.Text);
tbxConvertito.Text = (Math.Round(xDecimal, decimalPlace)).ToString();
}
if (numericUpDown1.Value == 1)
{
int decimalPlace = 1;
// Decimal xDecimal = decimal.Parse(tbxConvertito.text);
decimal xDecimal = decimal.Parse(tbxConvertito.Text);
tbxConvertito.Text = (Math.Round(xDecimal, decimalPlace)).ToString();
}
}
but not work. How can I solve this, please?

You should create field with decimal value, to keep original value.
If you do that:
int decimalPlace = 1;
decimal xDecimal = decimal.Parse(tbxConvertito.Text);
tbxConvertito.Text = (Math.Round(xDecimal, decimalPlace)).ToString();
You lose original value of your decimal variable.
Try this:
public partial class Form1 : Form
{
public decimal myDecimal = 3755.25012345M;
public Form1()
{
InitializeComponent();
tbxConvertito.Text = myDecimal.ToString();
numericUpDown1_ValueChanged(this, EventArgs.Empty);
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
int decimalPlace = (int)numericUpDown1.Value;
tbxConvertito.Text = Decimal.Round(myDecimal, decimalPlace).ToString();
}
}
Solution without use Round method:
public partial class Form1 : Form
{
public decimal myDecimal = 3755.25012345M;
public Form1()
{
InitializeComponent();
tbxConvertito.Text = myDecimal.ToString();
numericUpDown1_ValueChanged(this, EventArgs.Empty);
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
int decimalPlace = (int)numericUpDown1.Value;
string[] numbers = myDecimal.ToString().Split(new char[] { '.', ',' });
string tmp = string.Empty;
if (decimalPlace <= numbers[1].Length)
{
tmp = "," + numbers[1].Substring(0, decimalPlace);
if (tmp.EndsWith(","))
tmp = string.Empty;
}
else
tmp = "," + numbers[1];
tbxConvertito.Text = numbers[0] + tmp;
}
}

You can achieve this using String operations. Try this one
decimal xDecimal = decimal.Parse(tbxConvertito.Text);
string str = xDecimal.ToString();
if (!str.Contains(","))
decimalPlace--;
tbxConvertito.Text = str.Replace(",", "").Insert((str.Length-1) - decimalPlace,",");
And use it like this in your code
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
// tbxConvertito.Text = (decimal.Parse(tbxConvertito.Text) * 10m).ToString();
if (numericUpDown1.Value == 0)
{
int decimalPlace = 0;
// Decimal xDecimal = decimal.Parse(tbxConvertito.text);
decimal xDecimal = decimal.Parse(tbxConvertito.Text);
string str = xDecimal.ToString();
if (!str.Contains(","))
decimalPlace--;
tbxConvertito.Text = str.Replace(",", "").Insert((str.Length-1) - decimalPlace,",");
}
if (numericUpDown1.Value == 1)
{
int decimalPlace = 1;
// Decimal xDecimal = decimal.Parse(tbxConvertito.text);
decimal xDecimal = decimal.Parse(tbxConvertito.Text);
string str = xDecimal.ToString();
if (!str.Contains(","))
decimalPlace--;
tbxConvertito.Text = str.Replace(",", "").Insert((str.Length-1) - decimalPlace,",");
}
}

Related

Calculating multiple conversions through a combo box

So, below is as far as I've gotten. It keeps telling me I am unable to use a mathematical operator on a decimal or double. Unfortunately, those are what I have to use. What I'm trying to do is convert measurements of lengths from imperial to metric. I've looked through many other questions referring to this and was able to figure out parts of the code and how to get it to let me do an "if" statement. But I just can't figure out the math part of it. Can anyone point me in the right direction?
public partial class Form1 : Form
{
string conversions;
decimal meter, feet, centimeter, inches, miles, kilometers;
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
calculateConversions();
}
private void Form1_Load(object sender, EventArgs e)
{
cbConversion.SelectedText = "Miles to Kilometers";
string[] Conversion = new string[] { "Miles to Kilometers",
"Kilometers to Miles",
"Feet to Meters",
"Meters to Feet",
"Inches to Centimeters",
"Centermeters to Inches" };
{ }
for (int i = 0; i < Conversion.Length; i++)
{
cbConversion.Items.Add(Convert.ToString(Conversion[i]));
}
miles = 0m;
kilometers = 0m;
feet = 0m;
meter = 0m;
inches = 0m;
centimeter = 0m;
}
private void cbConversion_SelectedIndexChanged(object sender, EventArgs e)
{
conversions = Convert.ToString(cbConversion.SelectedItem);
IList<string> lstString = new List<string>();
lstString.Add("Miles:");
lstString.Add("Kilometers:");
lstString.Add("Feet:");
lstString.Add("Meters:");
lstString.Add("Inches:");
lstString.Add("Centimeters:");
label2.Text = lstString[cbConversion.SelectedIndex];
IList<string> lstStringTwo = new List<string>();
lstStringTwo.Add("Kilometers:");
lstStringTwo.Add("Miles:");
lstStringTwo.Add("Meters:");
lstStringTwo.Add("Feet:");
lstStringTwo.Add("Centimeters:");
lstStringTwo.Add("Inches:");
label3.Text = lstStringTwo[cbConversion.SelectedIndex];
}
private void calculateConversions()
{
decimal input = Convert.ToDecimal(txtInput.Text);
decimal output = Convert.ToDecimal(txtOutput.Text);
if (cbConversion.SelectedText == "Miles to Kilometers")
{
decimal miles = Convert.ToDecimal("");
}
I've even looked through my book and can't figure it out (it's a homework assignment)
The GUI I have. It's selected through the combobox and the entered text is calculated into the conversion. Everything works but the math
I added cbConversion.SelectedIndex = 0; in form1_load to select the first index of the combo box, then on calculateConversions() function in every condition i output in the textoutput.text.
Then the rest you can do else if and research for other formula for conversion.
And I used cbConversion.SelectedItem.ToString() so you can get item text from combobox to compare.
You can try this
string conversions;
decimal meter, feet, centimeter, inches, miles, kilometers;
private void btnCalculate_Click(object sender, EventArgs e)
{
calculateConversions();
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cbConversion.SelectedText = "Miles to Kilometers";
string[] Conversion = new string[] { "Miles to Kilometers",
"Kilometers to Miles",
"Feet to Meters",
"Meters to Feet",
"Inches to Centimeters",
"Centermeters to Inches" };
{ }
for (int i = 0; i < Conversion.Length; i++)
{
cbConversion.Items.Add(Convert.ToString(Conversion[i]));
}
miles = 0m;
kilometers = 0m;
feet = 0m;
meter = 0m;
inches = 0m;
centimeter = 0m;
cbConversion.SelectedIndex = 0;
}
private void cbConversion_SelectedIndexChanged(object sender, EventArgs e)
{
conversions = Convert.ToString(cbConversion.SelectedItem);
IList<string> lstString = new List<string>();
lstString.Add("Miles:");
lstString.Add("Kilometers:");
lstString.Add("Feet:");
lstString.Add("Meters:");
lstString.Add("Inches:");
lstString.Add("Centimeters:");
label2.Text = lstString[cbConversion.SelectedIndex];
IList<string> lstStringTwo = new List<string>();
lstStringTwo.Add("Kilometers:");
lstStringTwo.Add("Miles:");
lstStringTwo.Add("Meters:");
lstStringTwo.Add("Feet:");
lstStringTwo.Add("Centimeters:");
lstStringTwo.Add("Inches:");
label3.Text = lstStringTwo[cbConversion.SelectedIndex];
}
private void calculateConversions()
{
decimal input = Convert.ToDecimal(txtInput.Text);
decimal mileToKM = Convert.ToDecimal(1.609344);
if (cbConversion.SelectedItem.ToString() == "Miles to Kilometers")
{
decimal miles = (input * mileToKM);
txtOutput.Text = miles.ToString();
}
}
OUTPUT
#justinmontalban this is the code I'm using now
private void Form1_Load(object sender, EventArgs e)
{
cbConversion.SelectedText = "Miles to Kilometers";
string[] Conversion = new string[] { "Miles to Kilometers",
"Kilometers to Miles",
"Feet to Meters",
"Meters to Feet",
"Inches to Centimeters",
"Centermeters to Inches" };
{ }
for (int i = 0; i < Conversion.Length; i++)
{
cbConversion.Items.Add(Convert.ToString(Conversion[i]));
}
miles = 0m;
kilometers = 0m;
feet = 0m;
meter = 0m;
inches = 0m;
centimeter = 0m;
cbConversion.SelectedIndex = 0;
}
private void cbConversion_SelectedIndexChanged(object sender, EventArgs e)
{
conversions = Convert.ToString(cbConversion.SelectedItem);
IList<string> lstString = new List<string>();
lstString.Add("Miles:");
lstString.Add("Kilometers:");
lstString.Add("Feet:");
lstString.Add("Meters:");
lstString.Add("Inches:");
lstString.Add("Centimeters:");
label2.Text = lstString[cbConversion.SelectedIndex];
IList<string> lstStringTwo = new List<string>();
lstStringTwo.Add("Kilometers:");
lstStringTwo.Add("Miles:");
lstStringTwo.Add("Meters:");
lstStringTwo.Add("Feet:");
lstStringTwo.Add("Centimeters:");
lstStringTwo.Add("Inches:");
label3.Text = lstStringTwo[cbConversion.SelectedIndex];
}
private void calculateConversions()
{
decimal input = Convert.ToDecimal(txtInput.Text);
decimal mileToKM = Convert.ToDecimal(1.6093);
decimal kMToMile = Convert.ToDecimal(0.6214);
decimal ftToM = Convert.ToDecimal(0.3048);
decimal mToFt = Convert.ToDecimal(3.2808);
decimal inToCm = Convert.ToDecimal(2.54);
decimal cmToIn = Convert.ToDecimal(0.3937);
if (cbConversion.SelectedText.ToString() == "Miles to Kilometers")
{
decimal miles = (input * mileToKM);
txtOutput.Text = miles.ToString();
}

C# Calculator using List Array error at some operations Windows Form Application

Hello I'm still new to programming and yes this is not the best code you will see... I tried making calculator on C# windows form for fun and I'm having trouble on the subtraction and division operations, but the addition and multiplication works perfectly fine for me. I decided to have a list array so that I would be able to input numbers as much as I want.
The error for the subtraction is when I input for example 5 - 2 the result will be -3
As for the division the error is that the result is always 1
Please tell me where did I go wrong and give a detailed explanation if possible so that I would understand more about programming. Thanks in advance!
namespace CalculatorTestForm1
{
public partial class Form1 : Form
{
public static List<int> Numlist = new List<int>();
public static string operation;
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
Button Num = (Button)sender;
TXTBox.Text += Num.Text;
}
private void BPlus_Click(object sender, EventArgs e)
{
operation = "add";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BEquals_Click(object sender, EventArgs e)
{
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
int sum = 0;
int product = 1;
int quotient = 1;
int difference = 0;
if (operation == "add"){
foreach (int value in Numlist)
{
sum += value;
}
string Answer = sum.ToString();
TXTBox.Text = Answer;
}else if(operation == "minus"){
foreach (int value in Numlist)
{
difference = value - difference;
}
string Answer = difference.ToString();
TXTBox.Text = Answer;
}
else if (operation == "multiply")
{
foreach (int value in Numlist)
{
product *= value;
}
string Answer = product.ToString();
TXTBox.Text = Answer;
}
else if (operation == "divide")
{
foreach (int value in Numlist)
{
quotient = value / value;
}
string Answer = quotient.ToString();
TXTBox.Text = Answer;
}
Numlist.Clear();
}
private void BClear_Click(object sender, EventArgs e)
{
TXTBox.Text = "";
Numlist.Clear();
}
private void BMinus_Click(object sender, EventArgs e)
{
operation = "minus";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BDivide_Click(object sender, EventArgs e)
{
operation = "divide";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BMulti_Click(object sender, EventArgs e)
{
operation = "multiply";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
}
}
For the division it's obvious:
quotient = value / value;
value/value will always be 1.
There must be quotient in that loop somewhere...
For the subtraction the problem is that because of the way you do it, the order of the numbers are reversed.
lets say 5 - 2:
foreach (int value in Numlist)
{
difference = value - difference;
}
NumList = {5,2}
1st iteration:
difference = value(5) - difference(0) = 5
2nd iteration:
difference = value(2) - difference(5) = -3
You should reverse the order of the loop: NumList.Reverse()
And for the division as well:
Division:
foreach (int value in Numlist.Reverse())
{
quotient = value / quotient;
}
Subtraction:
foreach (int value in Numlist)
{
difference = value - difference;
}

freezing form after clicking button

I have a problem regarding to payment button.
I don't encounter an error before building, but after building and clicking the payment button it hangs. I think its because of lblTotalPrice.text, but I don't know how to fix it.
public partial class Form1 : Form
{
int totalCost;
public double holDer;
public Form1()
{
InitializeComponent();
this.cbo1.Items.AddRange(new object[] { "Lechon Kawali - 200", "Bicol Express - 300"
,"Adobo - 350" });
}
private void btnAdd_Click(object sender, EventArgs e)
{
lb1.Items.Add(cbo1.SelectedItem);
lb1.SelectedIndex = lb1.SelectedIndex ;
int z = 0;
if (cbo1.SelectedIndex == 0)
{
z = z + 1;
}
if (cbo1.SelectedIndex == 1)
{
z = z + 2;
}
if (cbo1.SelectedIndex == 2)
{
z = z + 3;
}
switch(z)
{
case 1:
totalCost = totalCost + 200;
break;
case 2:
totalCost = totalCost + 300;
break;
case 3:
totalCost = totalCost + 350;
break;
}
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
}
private void btnDelete_Click(object sender, EventArgs e)
{
int deleteCost = 0;
int itemCost = 0;
foreach (int selectedIndex in lb1.SelectedIndices)
{
itemCost = int.Parse(lb1.Items[selectedIndex].ToString().Split('-')[1]);
deleteCost += itemCost; lb1.Items.RemoveAt(selectedIndex);
}
totalCost = totalCost - deleteCost;
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
lb1.Items.Remove(lb1.SelectedItem);
if (lb1.Items.Count > 0)
{
lb1.SelectedIndex = 0;
}
else
MessageBox.Show("No orders");
}
private void lblVAT_TextChanged(object sender, EventArgs e)
{
Add();
}
private void lblSubTotalCost_TextChanged(object sender, EventArgs e)
{
multiply();
Add();
}
public void multiply()
{
int a;
double b = 0.12;
bool Valid = int.TryParse(totalCost.ToString(), out a);
if (Valid)
lblVAT.Text = (a * b).ToString();
else
lblVAT.Text = "No VAT entered";
}
private void lbTotalPrice_TextChanged(object sender, EventArgs e)
{
Add();
}
public void Add()
{
int a;
int b;
bool AValid = int.TryParse(totalCost.ToString(), out a);
bool BValid = int.TryParse(lblVAT.Text, out b);
if (AValid && BValid)
{
lblTotalPrice.Text = ("Php " + (a + b).ToString());
}
}
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
}
As you stated in your comments, your problem it is not that your application hangs, but the problem is that you are getting a Input string was not in a correct format Exception.
That it seems is from this block:
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
As it is a not very complex code, your problem seems to be when you are casting your textboxes to Double. Be sure that you are using the correct separator for double values and that you not have any strange characters in tbPayment
Try using TryParse method:
double res;
if(double.TryParse(tbPayment.Text, out res))
{
holDer = res - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
else
{
MessageBox.Show("Input a correct format");
}
I suspect it's because the lblTotalPrice_TextChanged event-handler calls Add() which then changes the lblTotalPrice.Text property, causing the event to fire again, ad -infinitum?

Multiplication in C# WPF

I'm trying to make a program that generates 2 random numbers, then, after the user inputs the multiplication of those numbers, it will tell the user in a MessageBox whether or not the user was right or wrong. Sort of like an educational simulator.
I'm having problems with the end part. What I'm saying is; If the answer is the same as number1 and number2 multiplied, then it says; "Rétt!" and if not; "Rangt..."
Any ideas?
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
int answer = 0;
tbnumber1.Text = number1.ToString();
tbnumber2.Text = number2.ToString();
if (svar == (number1 * number2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt...");
}
}
}
}
The full code.
public MainWindow()
{
InitializeComponent();
}
int tala1 = 0;
int tala2 = 0;
int svar = 0;
private void btstart_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = "";
tbtala2.Text = "";
tbsvar.Text = "";
Random random = new Random();
tala1 = random.Next(1, 11);
tala2 = random.Next(1, 11);
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
}
private void btend_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
tbsvar.Text = svar.ToString();
if (svar == (tala1 * tala2).ToString())
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
}
}
}
SOLVED. Thank you to everyone who did/tried to help.
Final Version:
Final Version:
public MainWindow()
{
InitializeComponent();
}
int tala1 = 0;
int tala2 = 0;
int svar = 0;
private void btstart_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = "";
tbtala2.Text = "";
tbsvar.Text = "";
Random random = new Random();
tala1 = random.Next(1, 11);
tala2 = random.Next(1, 11);
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
}
private void btend_Click(object sender, RoutedEventArgs e)
{
tala1 = Convert.ToInt32(tbtala1.Text);
tala2 = Convert.ToInt32(tbtala2.Text);
svar = Convert.ToInt32(tbsvar.Text);
if (svar == (tala1 * tala2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
To do this in a safe manner, you should not only Parse the text inputs to numbers, but you should also ensure that the text does in fact contain numbers first. If your numbers are supposed to be integers then you could use this:
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
if (int.TryParse(tbnumber1.Text, out number1) ||
int.TryParse(tbnumber12.Text, out number2)) MessageBox.Show("Rangt...");
MessageBox.Show(svar == number1 * number2 ? "Rétt!" : "Rangt...");
}
You're putting the numbers in the textbox values. you have to convert textbox values to numbers.
private void btend_Click(object sender, RoutedEventArgs e)
{
try{
tala1 = Convert.ToInt32(tbtala1.Text);
tala2 = Convert.ToInt32(tbtala2.Text);
svar = Convert.ToInt32(tbsvar.Text);
if (svar == (tala1 * tala2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
}catch{
MessageBox.Show("Invalid input");
}
}
You never define svar. You probably meant something like this, assuming svar was set earlier and is the correct product of the random multiplication:
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
number1 = int.Parse(tbnumber1.Text);
number2 = int.Parse(tbnumber2.Text);
if (svar == (number1 * number2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt...");
}
}
1.I observed that you have not initialized variable 'svar' anywhere.
Initialise your svar variable with proper value.
2.Replace This :
if (svar == (number1 * number2).ToString())
With Following :
if (svar == (number1 * number2))

Change decimal place in textbox value with numericUpDown

With this code I can modify decimal place, using numericUpDown. This code works if I initialize myDecimal variable. But I need modify decimal place to a value typed in textbox.
In other word myDecimal = tbxConvertito.Text. But in this case, code not work.
Check screenshot in this page please: change decimal place in textbox using numericUpDown
public partial class Form1 : Form
{
public decimal myDecimal = 3755.25012345M;
public Form1()
{
InitializeComponent();
tbxConvertito.Text = myDecimal.ToString();
numericUpDown1_ValueChanged(this, EventArgs.Empty);
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
int decimalPlace = (int)numericUpDown1.Value;
string[] numbers = myDecimal.ToString().Split(new char[] { '.', ',' });
string tmp = string.Empty;
if (decimalPlace <= numbers[1].Length)
{
tmp = "," + numbers[1].Substring(0, decimalPlace);
if (tmp.EndsWith(","))
tmp = string.Empty;
}
else
tmp = "," + numbers[1];
tbxConvertito.Text = numbers[0] + tmp;
}
}
You can split property Text from tbxConvertito.
Also when text will be changed in TextBox you must invoke numericUpDown1_ValueChanged to restrict settings in NumericUpDown.
public partial class Form1 : Form
{
public decimal myDecimal = 3755.25012345M;
public Form1()
{
InitializeComponent();
tbxConvertito.Text = myDecimal.ToString();
numericUpDown1_ValueChanged(this, EventArgs.Empty);
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
int decimalPlace = (int)numericUpDown1.Value;
string[] numbers = tbxConvertito.Text.Split(new char[] { '.', ',' });
string tmp = string.Empty;
if (numbers.Length != 1)
{
if (decimalPlace <= numbers[1].Length)
{
tmp = "," + numbers[1].Substring(0, decimalPlace);
if (tmp.EndsWith(","))
tmp = string.Empty;
}
else
tmp = "," + numbers[1];
}
tbxConvertito.Text = numbers[0] + tmp;
tbxConvertito.Select(tbxConvertito.Text.Length, 0);
}
private void tbxConvertito_TextChanged(object sender, EventArgs e)
{
numericUpDown1_ValueChanged(this, EventArgs.Empty);
decimal.TryParse(tbxConvertito.Text.Replace(',', '.'), out myDecimal);
}
}
Without lose data:
public partial class Form1 : Form
{
public decimal myDecimal = 0;
public Form1()
{
InitializeComponent();
// init value
tbxConvertito.Text = myDecimal.ToString();
numericUpDown1_ValueChanged(this, EventArgs.Empty);
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
int decimalPlace = (int)numericUpDown1.Value;
string[] numbers = myDecimal.ToString().Split(new char[] { '.', ',' });
string tmp = string.Empty;
if (numbers.Length != 1)
{
if (decimalPlace <= numbers[1].Length)
{
tmp = "," + numbers[1].Substring(0, decimalPlace);
if (tmp.EndsWith(","))
tmp = string.Empty;
}
else
tmp = "," + numbers[1];
}
tbxConvertito.Text = numbers[0] + tmp;
tbxConvertito.Select(tbxConvertito.Text.Length, 0);
}
private void tbxConvertito_TextChanged(object sender, EventArgs e)
{
if (keyValue == 188) return;
if (keyPressed)
{
string stringValue = tbxConvertito.Text;
if ((stringValue.Contains(',') && stringValue.Split(new char[] { ',' })[1].Length <= (int)numericUpDown1.Value) || !stringValue.Contains(','))
decimal.TryParse(tbxConvertito.Text.Replace(',', '.'), out myDecimal);
keyPressed = false;
}
numericUpDown1_ValueChanged(this, EventArgs.Empty);
Console.WriteLine("Displayed value: {0}", tbxConvertito.Text);
Console.WriteLine("Actual value: {0}", myDecimal);
}
bool keyPressed = false;
int keyValue;
private void tbxConvertito_KeyDown(object sender, KeyEventArgs e)
{
keyValue = e.KeyValue;
keyPressed = true;
}
}
Scenarios:
[Decimal Places = 0] you can type e.g. [1], [1234], [12345]
[Decimal Places = 1] you can type e.g. [1,1], [1234], [12345,3]
if
you change value in NumericUpDown to 0 displayed value will be [1],
[1234], [12345]
if you change value in NumericUpDown to 1 again
displayed value will be [1,1], [1234], [12345,3]
[Decimal Places = 1] the same situation as for step 2
Now we don't lose any data. We update our original data only if user will type something in our textbox.
Give it a try
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
//var ix = tbxConvertito.Text.IndexOf(',');
decimal myDecimal = 0;
bool IsDecimal = decimal.TryParse(tbxConvertito.Text, out myDecimal);
if (IsDecimal)
{
decimal letDivide = myDecimal / 100;
int decimalPlace = (int)numericUpDown1.Value;
tbxConvertito.Text = letDivide.ToString().Replace(".", "");
var index = tbxConvertito.Text.Length - decimalPlace;
if (index > -1)
tbxConvertito.Text = tbxConvertito.Text.Insert(index, ",");
else
tbxConvertito.Text = tbxConvertito.Text.Insert(1, ",");
}
else
{
tbxConvertito.Text = tbxConvertito.Text.ToString().Replace(",", "");
}
}

Categories

Resources