I want to create separate textbox for numbers and string using c# code. I should not use jquery or javascript. Can anyone pls help me.
Condition:
Numeric Textbox: It should not allow characters, special characters.
String Textbox: Should not allow numbers, Special characters.
I think you can use Masked C# TextBox Control
Have a look at the Validation Controls ; these include client-side (javascript) and server-side validation logic.
for numbers only
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
int isNumber = 0;
e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
}
for text only
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
int Length=textbox1.Length;
int Loop;
for(Loop=1;Loop<=Length;Loop++)
{
char c=textbox1.subString(Loop,1);
if(( c<'a' && c>'z') || (c<'A' && c>'Z'))
{
Messagebox.Show("Please Enter Only Alphabets");
e.Handle=true;
}
}
}
Related
I have a textbox, in Windows Form, for the input from a user. I want him to allow some punctuations but disallow others. How can I fix that? I have the next code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) &&
!char.IsLetter(e.KeyChar) &&
!char.IsPunctuation(e.KeyChar) &&
!char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
}
}
One way to approach this is to look at the string they inputted as an array of chars:
char[] strarray = userinput.ToCharArray();
And then just create an if statement to look for the punctuation for example:
if(strarray.Contains(' the punctuation you don't want')){
// provide user input to tell the user to input a new string and reset the text box
}
Hope that Helps
private void inputBox_KeyPress(object sender, KeyPressEventArgs e)
{
stringScan();
var regex1 = new Regex(#"[^+^\-^\b^\r\n]");
var regex2 = new Regex(#"[^0-9^+^\-^/^*^#^\b^\r\n]");
if (ListBox.Items.Count == 0 && string.IsNullOrWhiteSpace(inputBox.Text))
{
if (regex1.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
toolTip1.Show("Plus or minus first then followed by numbers.", inputBox, 1500);
}
}
else
{
if (regex2.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
}
}
}
public void stringScan()
{
char last_char = inputBox.ToString()[inputBox.ToString().Length - 1];
Console.WriteLine(last_char);
}
How can i get the last letter/number of a string?. Its really hard to explain so I'll show some screenshots.
the output should show "0" not "1".
It always show the "previews last" and not the latest one that i typed in the textbox.
Remember, when the event inputBox_KeyPress is raised, the typed key isn't added yet. Also, don't use regex for this. It will be overcomplicated.
Try the TextChanged event.
Text box key change will be executed every time u change the content of the text box
So for every value u enter u will be calling the string scan
This can be limited if u know what length the text is going to be
What about you try this:
public void stringScan()
{
String last_char = inputBox.ToString();
Console.WriteLine(last_char[last_char.Length-1]);
}
If you want last typed char I suggest:
private void inputBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Console.WriteLine(e.Text);
}
If you want last char in textbox I suggest TextChanged event as already told by Jeroen van Langen:
private void inputBox_TextChanged(object sender, TextChangedEventArgs e)
{
string inputString = ((TextBox)sender).Text;
char lastChar = inputString.Last();
Console.WriteLine(lastChar);
}
Hope code samples help you
Edit:
Now I get that you probably want to get integer from textbox, if that's the matter, Get integer from Textbox could help you, code sample:
private void inputBox_TextChanged(object sender, TextChangedEventArgs e)
{
string inputString = ((TextBox)sender).Text;
int valueFromTextBox;
if (int.TryParse(inputString, out valueFromTextBox))
{
//parsing successful
}
else
{
//parsing failed.
}
}
I have several text boxes and would like to format them all the same way with these rules:
// limits to number, control keys, and decimal
// goes to the next text box when enter
private void tb_text1_KeyPress_1(object sender, KeyPressEventArgs e)
{
string newString = Regex.Replace(tb_text1.Text, "[^.0-9]", "");
tb_text1.MaxLength = 6;
e.Handled = (!char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar) && e.KeyChar != '.');
if (e.KeyChar == (char)(Keys.Enter))
{
this.GetNextControl(ActiveControl, true).Focus();
}
}
// removes restricted chars
private void tb_text1_Enter(object sender, EventArgs e)
{
tb_text1.Text = Regex.Replace(tb_text1.Text, "[^.0-9]", "");
}
// applies format at exit
private void tb_text1_Leave(object sender, EventArgs e)
{
tb_text1.Text = string.Format("{0,-6} [Ohm]", decimal.Parse(tb_text1.Text));
}
What is the best way? create a new text box class based on the text box?
Thanks.
Replace in methods your "tb_text1" variable to the "((TextBox)sender)", and now You can use Your code for any textbox.
It is very easy to do it with javascript . Please try that. I have done it i'm not able to find piece of that code right now . It is worth the effort because it will be very fast and will be running on client side.
I have one TextBox with binding on DateTime type. I need to get a dot after first 2 chars and second 2 chars, for example: 12.12.1990.
I'm using behavior in TextChanged event, that code:
void tb_TextChanged(object sender, TextChangedEventArgs e)
{
int i = tb.SelectionStart;
if (i == 2 || i == 5)
{
tb.Text += ".";
tb.SelectionStart = i + 1;
}
}
That is working, but if I want to delete text by backspace, obviously I can't delete dots, because event is called again.
What is better way to solve it?
Solved
It works
But if you can, you may fix my algorithm.
public string oldText = "";
public string currText = "";
private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
oldText = currText;
currText = TextBox1.Text;
if (oldText.Length > currText.Length)
{
oldText = currText;
return;
}
if (TextBox1.Text.Length == currText.Length)
{
if (TextBox1.SelectionStart == 2 || TextBox1.SelectionStart == 5)
{
TextBox1.Text += ".";
TextBox1.SelectionStart = TextBox1.Text.Length;
}
}
}
I would do it in the KeyPress event, so you can filter by what kind of key it was (using the KeyChar argument with Char.IsLetter() and similar functions).
Also, add the dot when the next key is pressed. If the user has typed "12", don't add a dot yet. When the user presses 1 to add the second "12", add it then (before the new character).
Use String Format in the xaml control like so
StringFormat='{}{0:dd.MM.yyyy}'
I just tested it and this will even convert slashes to the dots.
For example
<TextBox.Text>
<Binding Path="Person.DateOfBirth" UpdateSourceTrigger="LostFocus" StringFormat='{}{0:dd.MM.yyyy}'></Binding>
</TextBox.Text>
If you are using a datepicker then you will need to override its textbox template as in the link below with the String Format above.
This link may help if if you are trying to apply it to a datepicker.
I recommend you to use a DateTimePicker and change its Format property to Short. Another option is to change your TextBox to a MaskedTextBox and changing its Mask property to ShortDate (00/00/0000) .DateTimePicker allows you not to do much about validating datetime values. But if you use a MaskedTextBox you should validate it. Sample link shows how to do validation.
I have modified above code
private void txt_in1_TextChanged(object sender, TextChangedEventArgs e)
{
int i = txt_in1.SelectionStart;
if (bsp1 != 1)
{
if (i == 2)
{
txt_in1.Text += ":";
txt_in1.SelectionStart = i + 1;
}
}
}
private void txt_in1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Back)
{
bsp1 = 1;
}
else
{
bsp1 = 0;
}
}
I have taken another event which is keyup (equivalent keypress event), In that whenever backspace is detected it will flag bsp1 variable, which intern stop the text change event to put ":". here "bsp1" is define as global variable. (Code is for wpf, c#).
So I have a Subtotal TextBox where an amount like $546.75 can be entered. Now, I want to make sure that only numbers, ONE decimal, One Dollar Symbol and commas allowed only every 3 places (100,000,000). Is this possible? Maybe not the commas, but at least the numbers, decimal, and dollar symbol.
Why you dont put the money sign "$" out side of the textBox (create a label just infrontof textBox), then you will not have to worry about this character, but only about numbers. And it looks better (in my opinion).
Then you can use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (Char)Keys.Back) //allow backspace (to delete)
{
e.Handled = !char.IsNumber(e.KeyChar);
}
}
All validation should be performed manually on KeyPress event.
Here described validation for numeric values values. You will need to check the '$' sign and decimals additionally.
I think you are using WinForms and not WPF. If that is the case then you could use System.Windows.Forms.ErrorProvider (you can drag-drop one from toolbox to your form) along with regular expressions to do the validation.
WARNING: The regex pattern string below may not do exactly you want but hopefully conveys the idea.
Some match examples... "$4,000.00", "-$4000.00", "-$400.00"
private void textBox1_Validating(object sender, CancelEventArgs e)
{
string error = null;
string pattern = #"^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$";
if (!Regex.IsMatch(textBox1.Text, pattern))
{
error = "Please enter a US currency value.";
e.Cancel = true;
}
errorProvider1.SetError((Control)sender, error);
}
There are a number of articles on numeric textboxes
Numeric TextBox
http://www.daniweb.com/software-development/csharp/threads/95153
http://www.codeproject.com/KB/vb/NumericTextBox.aspx
I use this one in my projects
http://www.codeproject.com/KB/edit/ValidatingTextBoxControls.aspx
//tb - is the name of text box
private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
char[] inputChar = e.Text.ToCharArray();
if (char.IsNumber(inputChar[0]))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
// another method.
if (char.IsDigit(inputChar[0]))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
Have you tried Ajax Controls?
http://www.aspsnippets.com/Articles/ASPNet-AJAX-FilteredTextBoxExtender-Control-Example.aspx
Simples. :)