System.FormatException : 'Input string was not in a correct format - c#

I am working on TextChanged event on Entry field. But It is showing:
Unhandled Exception: System.FormatException: Input string was not in a correct format.
I'm trying to enter numbers into an array of text boxes and show the SUM result inside a label text. any idea?
// the error is occurring right here
//.Where(x => double.Parse(x.tb.Text) <= 25.5)
//code
private void ValueCalculate()
{
range[0] = textBox37;
range[1] = textBox22;
range[2] = textBox32;
sumrange[0] = textBox30;
sumrange[1] = textBox31;
sumrange[2] = textBox21;
double result_25 = range
.Zip(sumrange, (tb, otb) => new { tb, otb })
.Where(x => double.Parse(x.tb.Text) <= 25.5)
.Sum(x => double.Parse(x.otb.Text)) / 12;
var finalresult = Math.Ceiling(result_25);
label80.Text = finalresult.ToString()
}
private void TextBox_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty((sender as TextBox).Text))
ValueCalculate();
}
textBox37.TextChanged += TextBox_TextChanged;
textBox37.TextChanged += TextBox_TextChanged;
......

Related

As the user types: Separate numbers with commas, and format it into currency in C#

I have a textbox called textBox1.
Goal: As soon as the user types in textBox1, I want the program to convert the numbers into currency format.
Example: If the user typed 123456, I want the program to separate the numbers 123,456 like so.
Below is the basic approach, when the text changes convert it into a decimal then change the text to the string representation of the decimal.
textBox1.TextChanged += (s,e) =>
{
var value = Decimal.Parse(textBox1.Text);
textBox1.Text = value.ToString("C");
}
You should also check for illegal number in textBox. Take a look at Decimal.TryParse.
Upon research I came across this code. This code did exactly what i wanted.
private void form_3_Load(object sender, EventArgs e)
{
textBox1.Text = "$0.00";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
///
//Remove previous formatting, or the decimal check will fail including leading zeros
string value = textBox1.Text.Replace(",", "")
.Replace("$", "").Replace(".", "").TrimStart('0');
decimal ul;
//Check we are indeed handling a number
if (decimal.TryParse(value, out ul))
{
ul /= 100;
//Unsub the event so we don't enter a loop
textBox1.TextChanged -= textBox1_TextChanged;
//Format the text as currency
textBox1.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul);
textBox1.TextChanged += textBox1_TextChanged;
textBox1.Select(textBox1.Text.Length, 0);
}
bool goodToGo = TextisValid(textBox1.Text);
btn_test.Enabled = goodToGo;
if (!goodToGo)
{
textBox1.Text = "$0.00";
textBox1.Select(textBox1.Text.Length, 0);
}
///
}
private bool TextisValid(string text)
{
Regex money = new Regex(#"^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$");
return money.IsMatch(text);
}
void tb_TextChanged(object sender, EventArgs e)
{
//Remove previous formatting, or the decimal check will fail
string value = textBox1.Text.Replace(",", "").Replace("$", "");
decimal ul;
//Check we are indeed handling a number
if (decimal.TryParse(value, out ul))
{
//Unsub the event so we don't enter a loop
textBox1.TextChanged -= tb_TextChanged;
//Format the text as currency
textBox1.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul);
textBox1.TextChanged += tb_TextChanged;
}
}

How to add a hyphen “-” to separate each entered or clicked value in Textbox from many buttons in C#?

I'm a beginner to C# (WinForms), now I have a problem how do I add the "-" to separate each value that clicked or entered from different buttons.
Example:
btn1 = "01", btn2 = "02", btn3="03", btn4 = "04"
If I click the first button the insert 01 to the TextBox, and if I also click the second button then insert 02 to the textbox again but the TextBox format should be 01-02 and so on.
How do I handle this statement in C#?
Edit: Here are the code I have tried:
private void txtFixedTypeTwo_TextChanged(object sender, EventArgs e)
{
string sVal = txtFixedTypeTwo.Text;
if (!string.IsNullOrEmpty(sVal))
{
if(txtFixedTypeTwo.Text.Length <= 11)
{
var cVal = sVal.Substring(sVal.Length - 2);
string nVal = sVal + "-" + cVal;
txtFixedTypeTwo.Text = nVal;
txtFixedTypeTwo.SelectionStart = txtFixedTypeTwo.Text.Length;
txtFixedTypeTwo.Focus();
}
}
}
The Button click event I do like this:
private void btn01_Click(object sender, EventArgs e)
{
if (focusedTextbox != null)
{
// put something in textbox
focusedTextbox.Text += "01";
}
}
public void Button1_Click(object sender, EventArgs e)
{
if(textBox.Text.Length > 0)
textBox.Text += "-";
Button butt = (Button)sender;
textBox.Text += butt.Text;
}
From what I understood you have Button.Text= 01,02 and so on. You need to add this event click for all the buttons.
Button butt = (Button)sender;
With this line you are taking the button which is clicked.
You could do it this way:
Action<string> append = t =>
textBox.Text +=
(textBox.Text.Length > 0 ? "-" : "") + t;
btn1.Click += (s, _) => append("01");
btn2.Click += (s, _) => append("02");
btn3.Click += (s, _) => append("03");
btn4.Click += (s, _) => append("04");
Just add this code into the Form1_Load method
Try this:
if(textBox1.Text.Length >= 2)
{
textBox1.Text += "-00"
}
else
{
textBox1.Text += "00"
}
What will happen is when the length of TextBox is greater than equal to 2 it will add "-".
First Click 00 Second Click 00-00 Third Click 00-00-00.
To prevent repetition, you need to create method.
void TextBoxValue(object sender, TextBox textBox, string value)
{
if(textBox.Text.Length >= 2)
{
textBox.Text += String.Format("-{0}", value)
}
else
{
textBox.Text += value;
}
}

What function to use in getting all textbox names in form using C#?

I want to know how can I get all the textbox names in a form using C#?
Here is my code in generating dynamically textboxes:
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 5; i++)
{
TextBox txtbox = new TextBox();
txtbox.Name = "txtbox" + i;
flowLayoutPanel1.Controls.Add(txtbox);
Label lbl = new Label();
lbl.Name = "lbl" + i;
lbl.Text = lbl.Name;
flowLayoutPanel2.Controls.Add(lbl);
}
}
private void button1_Click(object sender, EventArgs e)
{
string[] textBoxNamesArray = this.Controls.OfType<TextBox>()
.Select(r => r.Name)
.ToArray();
var textboxes = string.Join(",", textBoxNamesArray);
MessageBox.Show(textboxes);
}
You can use LINQ to get all the names of the controls of type TextBox from the current form. The following query will return you an array of strings containing all the names.
string[] textBoxNamesArray = flowLayoutPanel1.Controls.OfType<TextBox>()
.Select(r => r.Name)
.ToArray();
Remember to include using System.Linq;
I used this.controls . You can convert or add it.
for ( int x = 0; x < i; x++ )
{
TextBox txtbox= ( TextBox )this.Controls["txtbox" + ( x + 1 ).ToString()];
double commissions = Convert.ToDouble( txtbox.Text ) / 100;
}
If you can use .NET 4.0 with LINQ you can use the following code
ArrayList list = new ArrayList(control.Controls);
var names = list.ToArray()
.Where(src => src is TextBox)
.Select(src => (src as TextBox).Name);
The Method which is provided by Habib is a little bit better ;)

How to paste 12 consecutive digit numbers into 4 text boxes using TextChanged property?

I am trying to be able to paste (mouse or keyboard shortcut) a 12 digit number (IP address, but no periods between) into 4 fields. Each has maximum length of 3.
I am trying to do this by using TextChange, text box, property. I was trying to use Substring but it doesn't each octet work.
public PingIPRange()
{
InitializeComponent();
txtF1.TextChanged += new EventHandler(NextField);
txtF2.TextChanged += new EventHandler(NextField);
txtF3.TextChanged += new EventHandler(NextField);
}
private void NextField(object sender, EventArgs e)
{
if (txtF1.TextLength == 3)
{
txtF2.Focus();
txtF1.Text = txtF1.Text.Substring(0, 3);
txtF2.Text = txtF1.Text.Substring(3, 30);
}
if (txtF2.TextLength == 3)
{
txtF3.Text = txtF2.Text.Substring(3, 27);
txtF3.Focus();
}
if (txtF3.TextLength == 3)
{
txtF4.Focus();
}
}
Try putting this code in NextField method. And hookup only to txtF1 textbox textchange event.
TextBox txt = (TextBox) sender;
var s1 = txt.Text.Split('.');
if(s1.Length==4)
{
txtF1.Text = s1[0];
txtF2.Text = s1[1];
txtF3.Text = s1[2];
txtF4.Text = s1[3];
}
UPDATE: As you have updated the question that there will not be any dot symbol you can split string like this
var s1=Enumrable
.Range(0,4)
.Select(i => txt.Text.Substring(i * 3, 3))
.ToArray();
This wont work so well as you're trying to change text within the TextChanged handler - so it will fire itself again. Why not just have the event handler change focus to the next box when the length is 3, that way you avoid a cyclic loop.
Works only if it's pasted in TextF1.
public PingIPRange()
{
InitializeComponent();
txtF1.TextChanged += new EventHandler(PasteNumbers);
}
private void PasteNumbers(object sender, EventArgs e)
{
if (txtF1.TextLength > 9) { txtF4.Text = txtF1.Text.Substring(9, 3); }
if (txtF1.TextLength > 6) { txtF3.Text = txtF1.Text.Substring(6, 3); }
if (txtF1.TextLength > 3)
{
txtF2.Text = txtF1.Text.Substring(3, 3);
txtF1.Text = txtF1.Text.Substring(0, 3);
}
}
Edit, to be totally correct, you need to do a min between (txtF1.TextLength - 9) and the 3 in the Substring not to have OutOfBound problems for txtF4, and the same for txtF3 and txtF2.
You could you the KeyUp and MouseUp events on txtF1 and use the following code:
private void txtF1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
PasteText();
}
}
private void txtF1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right &&
((TextBox)sender).Modified)
{
PasteText();
}
}
private void PasteText()
{
string[] val = txtF1.Text.Split('.');
txtF1.Text = val[0].ToString();
txtF2.Text = val[1].ToString();
txtF3.Text = val[2].ToString();
txtF4.Text = val[3].ToString();
}
NOTE: I haven't included any error handling.

Textbox display formatting

I want to add "," to after every group of 3 digits. Eg : when I type 3000000 the textbox will display 3,000,000 but the value still is 3000000.
I tried to use maskedtexbox, there is a drawback that the maskedtexbox displayed a number like _,__,__ .
Try adding this code to KeyUp event handler of your TextBox
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
int valueBefore = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
textBox1.Text = String.Format(culture, "{0:N0}", valueBefore);
textBox1.Select(textBox1.Text.Length, 0);
}
}
Yes, it will change the value stored in a texbox, but whenever you need the actual number you can use the following line to get it from the text:
int integerValue = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
Of course do not forget to check that what the user inputs into the textbox is actually a valid integer number.
Use String.Format
int value = 300000
String.Format("{0:#,###0}", value);
// will return 300,000
http://msdn.microsoft.com/en-us/library/system.string.format.aspx
This may work fine for your scenario I hope.
private string text
{
get
{
return text;
}
set
{
try
{
string temp = string.Empty;
for (int i = 0; i < value.Length; i++)
{
int p = (int)value[i];
if (p >= 48 && p <= 57)
{
temp += value[i];
}
}
value = temp;
myTxt.Text = value;
}
catch
{
}
}
}
private void digitTextBox1_TextChanged(object sender, EventArgs e)
{
if (myTxt.Text == "")
return;
int n = myTxt.SelectionStart;
decimal text = Convert.ToDecimal(myTxt.Text);
myTxt.Text = String.Format("{0:#,###0}", text);
myTxt.SelectionStart = n + 1;
}
Here, myTxt = your Textbox. Set Textchanged event as given below and create a property text as in the post.
Hope it helps.
You could hook up to OnKeyUp event like this:
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!(e.KeyCode == Keys.Back))
{
string text = textBox1.Text.Replace(",", "");
if (text.Length % 3 == 0)
{
textBox1.Text += ",";
textBox1.SelectionStart = textBox1.Text.Length;
}
}
}
Get Decimal Value Then set
DecimalValue.ToString("#,#");

Resources