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(",", "");
}
}
Related
I have 3 textboxes in which I write numbers and last one in which is the result. If I write numbers in TextBoxA and TextBoxB instead of adding them together after I press equal button then it put them next to each other.
[]
I tried this code:
private void EqualsButton_Click(object sender, EventArgs e)
{
OutputTextBox.Text = ($"{InputTextBoxA.Text + InputTextBoxB.Text}");
}
First you must convert text on textbox to int or any number type
Simple way :
private void EqualsButton2_Click(object sender, EventArgs e)
{
int numberA = int.Parse(textBox1.Text.Trim());
int numberB = int.Parse(textBox2.Text.Trim());
var result = numberA + numberB;
textBox3.Text = result.ToString();
}
Safe way :
private void EqualsButton_Click(object sender, EventArgs e)
{
if (!int.TryParse(textBox1.Text.Trim(), out int numberA))
numberA = 0;
if (!int.TryParse(textBox2.Text.Trim(), out int numberB))
numberB = 0;
var result = numberA + numberB;
textBox3.Text = result.ToString();
}
Don't listen to anyone. Do this
txtResult.Text = string.Empty;
if (!decimal.TryParse(txt1.Text.Trim(), out decimal v1))
{
MessageBox.Show("Bad value in txt1");
return;
}
if (!decimal.TryParse(txt2.Text.Trim(), out decimal v2))
{
MessageBox.Show("Bad value in txt2");
return;
}
txtResult.Text = (v1 + v2).ToString();
private void EqualsButton_Click(object sender, EventArgs e)
{
var resultA=0;
var resultB=0;
if(!string.IsNullOrEmpty(InputTextBoxA.Text))
resultA=Convert.ToInt32(InputTextBoxA.Text);
if(!string.IsNullOrEmpty(InputTextBoxB.Text))
resultB=Convert.ToInt32(InputTextBoxB.Text);
OutputTextBox.Text = resultA+ resultB ;
}
You can change into this
private void EqualsButton_Click(object sender, EventArgs e)
{
try
{
OutputTextBox.Text = ($"{ Convert.ToInt32(InputTextBoxA.Text.Trim() == "" ? "0" : InputTextBoxA.Text) + Convert.ToInt32(InputTextBoxB.Text.Trim() == "" ? "0" : InputTextBoxB.Text)}");
}
catch(exception ex)
{
MessageBox.Show("Enter Valid number")'
}
}
You need to convert text fields to int and after for the answer back to the text.
If you did not enter a value, then there "" is considered as 0 when adding.
private void EqualsButton_Click(object sender, EventArgs e)
{
OutputTextBox.Text = Convert.ToString(
Convert.ToInt32(InputTextBoxA.Text == "" ? "0" : InputTextBoxA.Text)
+ Convert.ToInt32(InputTextBoxB.Text == "" ? "0" : InputTextBoxB.Text));
}
What I have tried :
I am able to achieve both scenarios separately but only one works if adding the code together on the TextChanged event.
1)Add $sign in starting and ending of text as user types in Textbox code:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string symbol = "$";
if (TB.Text != "" && !TB.Text.StartsWith("$"))
{
var selectionIndex = TB.SelectionStart;
TB.Text = TB.Text.Insert(selectionIndex, symbol);
TB.SelectionStart = selectionIndex + symbol.Length;
}
}
2)Formatting comma-separated(thousand separators)values as user types in textbox code:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var TB = sender as TextBox;
string textValue = TB.Text.Replace(",", "");
if (double.TryParse(textValue, out result))
{
TB.TextChanged -= TextBox_TextChanged;
TB.Text = string.Format("{0:#,#}", result);
TB.SelectionStart = TB.Text.Length;
TB.TextChanged += TextBox_TextChanged;
}
}
Desired Output - $3,333.55$
Decimal point getting dynamically 2, 3, 4 decimals
like $4,566.444$, $3,3,456.33$ and so on
This is a simple string handling task:
private int DecimalPlaces { get; set; } = 3;
private char Delimiter { get; set; } = '$';
private void TextBox_TextInput(object sender, EventArgs e)
{
var textBox = sender as TextBox;
var plainInput = textBox.Text.Trim(this.Delimiter);
if (plainInput.EndsWith(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator))
{
return;
}
if (double.TryParse(plainInput, NumberStyles.Number, CultureInfo.CurrentCulture, out double number))
{
var decimalPlacesFormatSpecifier = GetNumberFormatSpecifier(this.DecimalPlaces);
textBox.Text = $"{this.Delimiter}{number.ToString(decimalPlacesFormatSpecifier, CultureInfo.CurrentCulture)}{this.Delimiter}";
}
}
private string GetNumberFormatSpecifier(int decimalPlaces)
{
var specifierBuilder = new StringBuilder("#,#");
if (decimalPlaces < 1)
{
return specifierBuilder.ToString();
}
specifierBuilder.Append(".");
for (int count = 0; count < decimalPlaces; count++)
{
specifierBuilder.Append("#");
}
return specifierBuilder.ToString();
}
To make the above solution robust, you must validate the input:
ensure that the user can only input numbers and
ensure that the caret can't be moved before the leading '$' and after the trailing '$'. To accomplish this you have to track the caret position.
I just need help on how to annotate a changed item in the list box if the user changes something using the text boxes provided.
namespace HW1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] values = new string[5];
values[0] = textBox1.Text;
values[1] = textBox2.Text;
values[2] = textBox3.Text;
values[3] = textBox4.Text;
values[4] = textBox5.Text;
string[] temp = new string[5];
temp[0] = textBox1.Text;
temp[1] = textBox2.Text;
temp[2] = textBox3.Text;
temp[3] = textBox4.Text;
temp[4] = textBox5.Text;
if(temp != values)
{
listBox1.SelectedIndex = 0 + "*";
listBox1.Text = values[1] + "*";
listBox1.Text = values[2] + "*";
listBox1.Text = values[3] + "*";
listBox1.Text = values[4] + "*";
}
listBox1.Items.Clear();
for (int i = 0; i < values.Length; i++)
{
listBox1.Items.Add(values[i].ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
The program will simply replace the old input from the text box with the new without displaying a * next to the item that has changed.
Your code doesn't actually compile... not sure how this line would ever work...
listBox1.SelectedIndex = 0 + "*";
Anyway - the main problem is that your for loop adds in values without the star to the list box
for (int i = 0; i < values.Length; i++)
{
listBox1.Items.Add(values[i].ToString()); //values[i] never has a star stored in it!
}
How about something like this...?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] values = new [] { textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text };
for (int i = 0; i < values.Length; i++)
{
if (listBox1.Items.Count < i + 1)
{
listBox1.Items.Add(values[i].ToString());
continue;
}
string unedited = listBox1.Items[i].ToString();
if (!string.IsNullOrEmpty(unedited) && unedited.Last() == '*')
unedited = listBox1.Items[i].ToString().Substring(0, listBox1.Items[i].ToString().Length - 1);
if (unedited != values[i])
listBox1.Items[i] = values[i] + "*";
else
listBox1.Items[i] = values[i];
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
This compares the list items to the textbox values.
If the textbox value doesn't exist, a listbox item is created.
If the listbox item doesn't match the textbox value, it has a * appended to it.
If an existing value (ignoring the star) is the same as the textbox value, it is updated to ensure the star is removed.
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?
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,",");
}
}