Textbox display formatting - c#

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("#,#");

Related

Add $ sign in starting and end of textbox as well as format value as comma separated(thousand separated) values in textbox WPF C#

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.

Fill a textbox based on another textbox text

I have TextBoxA and TextBoxB. What i want to do is , whenever i put a number (yes, both of the textboxes values are always integers) in TextBoxA , TextBoxB should "autocomplete" with value (100-TextBoxA). Same thing goes for TextBoxB. The sum of TextBoxA and TextBoxB should always be 100.
Here's what i've already tried:
static void TextBoxA_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-a).ToString();
TextBoxB.Text = text;
}
Static void TextBoxB_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-b).ToString();
TextBoxA.Text = text;
}
But it doesn't work.
Here's what you can try:
private void TextBoxA_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxA.Text, out num))
{
string text = (100 - num).ToString();
TextBoxB.Text = text;
}
}
private void TextBoxB_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxB.Text, out num))
{
string text = (100 - num).ToString();
TextBoxA.Text = text;
}
}
This will autocomplete on either TextBox on TextChanged Event.
First, i dont know why your event handlers are declared static.. its usually got to be :
private void TextBoxA_TextChanged(object sender, EventArgs e) { }
Secondly, you know if you have 2 textboxs, and each one triggers the other, you'll never go out of the TextChanged event.
To understand me more, here's an example :
1- You set TextBoxB.text = "1";2- TextBoxB.TextChanged triggers, it
sets TextBoxA.Text = "2"; 3- TextBoxA.TextChanged triggers, it sets
TextBoxB.Text = "1";
And it continues like this until i believe you'll get an Exception of memory.
EDIT : The opertator '-' works on numbers. You can't substract a number from a string. they have to be both numbers, so convert them first.
EDIT 2 :
Here's a code i wrote that works fine
private void textBox1_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox1.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox2.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox2.Text = m.ToString();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox2.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox1.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox1.Text = m.ToString();
}
}
Try this. This is a more efficient and elegant way I'd choose using lambda expressions, without repeating the method:
private void onChangeDoSum(object sender, EventArgs e,
TextBox substractNumber, TextBox sumNumber)
{
sumNumber.Text = (100 - Int32.Parse(substractNumber.Text)).ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox1, textBox2);
textBox2.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox2, textBox1);
}
Alternatively use Int32.TryParse to prevent unexpected results.
I think you can do something like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = (100 - Int32.Parse(textBox1.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = (100 - Int32.Parse(textBox2.Text)).ToString();
}
when I see that static word I think you have tried to create these method by yourself and you forgot to add
textBox1.TextChanged += textBox1_Changed;
// I saw other post where you wrote that it could raise exception and fall. Of course it can. You can use if condition like
textBox1.Text != null && textBox1.Text != ""
before value would be changed or TryParse() method

comma separator for datagridview textbox columns

I need Currency TextBox in DataGridView , I search Internet and Find this solution [^]
But this is useful when dataGridView Cell Leave event,I need comma separator in textchange ,
However I write this source for this purpose :
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox txt_edit = e.Control as TextBox;
if (txt_edit != null)
{
txt_edit.TextChanged += new EventHandler(txt_edit_TextChanged);
}
}
private void txt_edit_TextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox) sender;
string str = txt.Text;
str = str.Replace(",", "");
int len = str.Length;
if (len > 3)
{
str = str.Insert(len - 3, ",");
len = len - 3;
while (len > 3)
{
str = str.Insert(len - 3, ",");
len = len - 3;
}
}
dataGridView1.EndEdit();
dataGridView1.CurrentRow.Cells[0].Value = str;
dataGridView1.BeginEdit(false);
}
when i run my program and input number this source work correctly for 3 first digit , until type fourth number cording this error:
why this error cording?
Is there a better way to solve the problem?
tnx
Replace this:
dataGridView1.EndEdit();
dataGridView1.CurrentRow.Cells[0].Value = str;
dataGridView1.BeginEdit(false);
With:
int selStartFromEnd = txt.Text.Length - txt.SelectionStart;
txt.TextChanged -= txt_edit_TextChanged;
txt.Text = str;
txt.TextChanged += txt_edit_TextChanged;
if (txt.Text.Length - selStartFromEnd >= 0)
txt.SelectionStart = txt.Text.Length - selStartFromEnd;
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
This should work....(Not 100% sure)
delegate void SetColumnIndex();
private void txt_edit_TextChanged(object sender, EventArgs e)
{
//.....
dataGridView1.EndEdit();
SetColumnIndex method = new SetColumnIndex(Mymethod);
dataGridView1.CurrentRow.Cells[0].Value = str;
dataGridView1..BeginInvoke(method);
}
private void Mymethod()
{
dataGridView1.CurrentCell = myGridView.CurrentRow.Cells[0];
dataGridView1.BeginEdit(false);
}

c# error: Input string not in correct format

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();

To Disable Negative Values Inside a TextBox

I m Working On A windows Form.. I Need my TextBox Not To Accept negative Values ..How Can I Do this..
IS There Any Property Availiable For Doing The same...
You need to write keypress event of textbox like :
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You can also user numeric updown control to prevent negetive values.
UPDATE :
Ref: Sai Kalyan Akshinthala
My code will not handle the case of copy/paste. User can enter negative values by copy/paste. So I think Sai Kalyan Akshinthala's answer is correct for that case except one small change of Length >= 2.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
}
yes you can do write the following code part in textchanged event of textbox
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
just use min and pattern will not allow to enter a minus value
min="0" pattern="^[0-9]+$" in input type

Categories

Resources