How to move the textbox caret to the right - c#

I would like to change all the characters entered into a textbox to upper case. The code will add the character, but how do I move the caret to the right?
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
textBox3.Text += e.KeyChar.ToString().ToUpper();
e.Handled = true;
}

Set the CharacterCasing property of the TextBox to Upper; then you don't need to process it manually.
Note that textBox3.Text += e.KeyChar.ToString().ToUpper(); will append the new character to the end of the string even if the input caret is in the middle of the string (which most users will find highly confusing). For the same reason we cannot assume that the input caret should appear at the end of the string after inputting the character.
If you would still really want to do this in code, something like this should work:
// needed for backspace and such to work
if (char.IsControl(e.KeyChar))
{
return;
}
int selStart = textBox3.SelectionStart;
string before = textBox3.Text.Substring(0, selStart);
string after = textBox3.Text.Substring(before.Length);
textBox3.Text = string.Concat(before, e.KeyChar.ToString().ToUpper(), after);
textBox3.SelectionStart = before.Length + 1;
e.Handled = true;

tbNumber.SelectionStart = tbNumber.Text.ToCharArray().Length;
tbNumber.SelectionLength = 0;

private void txtID_TextChanged(object sender, EventArgs e)
{
txtID.Text = txtID.Text.ToUpper();
txtID.SelectionStart = txtID.Text.Length;
}

This will preserve the location of the insertion point (but persionally I'd go with the answer given by Fredrik Mörk)
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
int selStart = textBox3.SelectionStart;
textBox3.Text += e.KeyChar.ToString().ToUpper();
textBox3.SelectionStart = selStart;
e.Handled = true;
}
SelectionStart might actually be called SelStart, I don't have a compiler handy at the moment.

If you have to do this manually, you can use
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
textBox3.Text += e.KeyChar.ToString().ToUpper();
textBox3.SelectionStart = textBox3.Text.Length;
e.Handled = true;
}
But the preceding code inserts the new character at the end of the text. If you want to insert it at where the cursor is:
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
int selStart = textBox3.SelectionStart;
textBox3.Text = textBox3.Text.Insert(selStart,e.KeyChar.ToString().ToUpper());
textBox3.SelectionStart = selStart + 1;
e.Handled = true;
}
This code inserts the new character at the cursor position and moves the cursor to the left of the newly inserted character.
But i still think setting CharacterCasing is better.

Another method is to just change the value of the KeyChar itself:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
if ((int)e.KeyChar >= 97 && (int)e.KeyChar <= 122) {
e.KeyChar = (char)((int)e.KeyChar & 0xDF);
}
}
Although, using the CharacterCasing property is the easiest solution.

Related

C# TextBox convert numbers

I have textbox that I managed to accept numbers only by KeyPress but I cannot make input numbers separated by commas.
private void inputAmount_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
// this doesn't work
inputAmount.Text = string.Format("{0:#,##}", e.KeyChar);
}
}
What I'm looking for is: when user starts typing numbers in text box it separate thousands by commas while user typing.
Any idea?
Update
I've added second function TextChanged as following and removed inputAmount.Text = string.Format("{0:#,##}", e.KeyChar); line from code above.
It does add thousands separators to my input but it keeps jumping to beginning of the numbers
private void inputAmount_TextChanged(object sender, EventArgs e)
{
inputAmount.Text = string.Format("{0:#,##0}", double.Parse(inputAmount.Text));
}
Solved
Here is my final code that solved the issue
// Only accept numbers
private void inputAmount_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
}
// Add thousand separators while user typing
private void inputAmount_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(inputAmount.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
int valueBefore = Int32.Parse(inputAmount.Text, System.Globalization.NumberStyles.AllowThousands);
inputAmount.Text = String.Format(culture, "{0:N0}", valueBefore);
inputAmount.Select(inputAmount.Text.Length, 0);
}
}
Check with int.TryParse whether the input text is a number .
Then add the inputAmount string with the current character and convert it to the desired format.
Then place the CaretIndex at the end of the control with inputAmount.SelectionStart.
The following code shows how to do this
private void inputAmount_KeyPress(object sender, KeyPressEventArgs e)
{
int number = 0;
bool success = int.TryParse(e.KeyChar.ToString(), out number);
if (success)
{
string input = (inputAmount.Text + e.KeyChar).Replace(",", "");
inputAmount.Text = String.Format("{0:n0}", Convert.ToInt32(input));
inputAmount.SelectionStart = inputAmount.Text.Length;
e.Handled = true;
}
}

How to write a character only once in textbox?

I'm making a textbox to input some Product's Price, and I don't want the user to input "." more than once. "." can not be the first character (which I know how to do). But I need to make the textbox accept this character "." not more than once. How ? And no, I don't want to use MaskedTextBox.
Put it in KeyPress event in your textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string inputChar = e.KeyChar.ToString();
if (inputChar == ".")
{
if (textBox1.Text.Trim().Length == 0)
{
e.Handled = true;
return;
}
if (textBox1.Text.Contains("."))
{
e.Handled = true;
}
}
}
Try this
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.IndexOf('.') != textBox1.Text.LastIndexOf('.'))
{
MessageBox.Show("More than once, not allowed");
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
}
}

How to stop the first character in a text box from being '.'?

This is the code I currently have:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) && e.KeyChar != '.';
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) e.Handled = true;
}
KeyPress isn't good enough to do this kind of validation. A simple way to bypass it is to paste text into the text box with Ctrl+V. Or the context menu, no key event at all.
In this specific case, the TextChanged event will get the job done:
private void textBox_TextChanged(object sender, EventArgs e) {
var box = (TextBox)sender;
if (box.Text.StartsWith(".")) box.Text = "";
}
But there's a lot more to validating numeric values. You also need to reject stuff like 1.1.1 or 1.-2 etcetera. Use the Validating event instead. Drop an ErrorProvider on the form and implement the event like this:
private void textBox_Validating(object sender, CancelEventArgs e) {
var box = (TextBox)sender;
decimal value;
if (decimal.TryParse(box.Text, out value)) errorProvider1.SetError(box, "");
else {
e.Cancel = true;
box.SelectAll();
errorProvider1.SetError(box, "Invalid number");
}
}
You probably want to use the TextChanged event, since the user could paste in values. For the best experience given the requirements, I'd suggest simply removing any leading . characters.
void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.StartsWith("."))
{
textBox1.Text = new string(textBox1.Text.SkipWhile(c => c == '.').ToArray());
}
}
This does not address a requirement to use only digits -- wasn't clear in the question if that is the case.
This works for copy and pasting too.
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
int decimalCount=0;
string rebuildText="";
for(int i=0; i<textBox1.Text.Length; i++)
{
if (textBox1.Text[i] == '.')
{
if (i == 0) break;
if (decimalCount == 0)
rebuildText += textBox1.Text[i];
decimalCount++;
}
else if ("0123456789".Contains(textBox1.Text[i]))
rebuildText += textBox1.Text[i];
}
textBox1.Text = rebuildText;
textBox1.SelectionStart = textBox1.Text.Length;
}
You can try this:
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox.Text = TextBox.Text.TrimStart('.');
}

How to make a TextBox accept only alphabetic characters?

How can I make a TextBox only accept alphabetic characters with spaces?
You could use the following snippet:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]"))
{
MessageBox.Show("This textbox accepts only alphabetical characters");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
You can try by handling the KeyPress event for the textbox
void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
Additionally say allow backspace in case you want to remove some text, this should work perfectly fine for you
EDIT
The above code won't work for paste in the field for which i believe you will have to use TextChanged event but then it would be a bit more complicated with you having to remove the incorrect char or highlight it and place the cursor for the user to make the correction Or maybe you could validate once the user has entered the complete text and tabs off the control.
private void textbox1_KeyDown_1(object sender, KeyEventArgs e)
{
if (e.Key >= Key.A && e.Key <= Key.Z)
{
}
else
{
e.Handled = true;
}
}
The simplest way is to handle the TextChangedEvent and check what's been typed:
string oldText = string.Empty;
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text.All(chr => char.IsLetter(chr)))
{
oldText = textBox2.Text;
textBox2.Text = oldText;
textBox2.BackColor = System.Drawing.Color.White;
textBox2.ForeColor = System.Drawing.Color.Black;
}
else
{
textBox2.Text = oldText;
textBox2.BackColor = System.Drawing.Color.Red;
textBox2.ForeColor = System.Drawing.Color.White;
}
textBox2.SelectionStart = textBox2.Text.Length;
}
This is a regex-free version if you prefer. It will make the text box blink on bad input.
Please note that it also seems to support paste operations as well.
Write Code in Text_KeyPress Event as
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsLetter(e.KeyChar))
{
e.Handled = true;
}
}
This one is working absolutely fine...
private void manufacturerOrSupplierTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar) || char.IsLetter(e.KeyChar))
{
return;
}
e.Handled = true;
}
This solution uses regular expressions, does not allow invalid characters to be pasted into the text box and maintains the cursor position.
using System.Text.RegularExpressions;
int CursorWas;
string WhatItWas;
private void textBox1_Enter(object sender, EventArgs e)
{
WhatItWas = textBox1.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]*$"))
{
WhatItWas = textBox1.Text;
}
else
{
CursorWas = textBox1.SelectionStart == 0 ? 0 : textBox1.SelectionStart - 1;
textBox1.Text = WhatItWas;
textBox1.SelectionStart = CursorWas;
}
}
Note: textBox1_TextChanged recursive call.
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]+$"))
{
}
else
{
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
MessageBox.Show("Enter only Alphabets");
}
Please Try this
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9')
e.Handled = true;
else
e.Handled = false;
}
Try This
private void tbCustomerName_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back||e.KeyChar==(char)Keys.Space);
}
It Allows White Spaces Too
you can try following code that alert at the time of key press event
private void tbOwnerName_KeyPress(object sender, KeyPressEventArgs e)
{
//===================to accept only charactrs & space/backspace=============================================
if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
e.Handled = true;
base.OnKeyPress(e);
MessageBox.Show("enter characters only");
}
Here is my solution and it works as planned:
string errmsg = "ERROR : Wrong input";
ErrorLbl.Text = errmsg;
if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
ErrorLbl.Text = "ERROR : Wrong input";
}
else ErrorLbl.Text = string.Empty;
if (ErrorLbl.Text == errmsg)
{
Nametxt.Text = string.Empty;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) &&
(e.KeyChar !='.'))
{
e.Handled = true;
MessageBox.Show("Only Alphabets");
}
}
Try following code in KeyPress event of textbox
if (char.IsLetter(e.KeyChar) == false &
Convert.ToString(e.KeyChar) != Microsoft.VisualBasic.Constants.vbBack)
e.Handled = true
works for me, even though not the simplest one.
private void Alpha_Click(object sender, EventArgs e)
{
int count = 0;
foreach (char letter in inputTXT.Text)
{
if (Char.IsLetter(letter))
{
count++;
}
else
{
count = 0;
}
}
if (count != inputTXT.Text.Length)
{
errorBox.Text = "The input text must contain only alphabetic characters";
}
else
{
errorBox.Text = "";
}
}
This works fine as far as characters restriction, Any suggestions on error msg prompt with my code if it's not C OR L
Private Sub TXTBOX_TextChanged(sender As System.Object, e As System.EventArgs) Handles TXTBOX.TextChanged
Dim allowed As String = "C,L"
For Each C As Char In TXTBOX.Text
If allowed.Contains(C) = False Then
TXTBOX.Text = TXTBOX.Text.Remove(TXTBOX.SelectionStart - 1, 1)
TXTBOX.Select(TXTBOX.Text.Count, 0)
End If
Next
End Sub
Try this one. Spaces and shortcut keys work
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsSeparator(e.KeyChar))
{
e.Handled = true;
}

Autocomplete AND preventing new input - combobox

How can I allow the users of my program to type in a value and have it auto-complete, however, I also what to prevent them from entering new data because it would cause the data to be unfindable (unless you had direct access to the database).
Does anyone know how to do this?
The reasoning behind not using just a dropdown style combobox is because entering data by typing it is and then refusing characters that are not part of an option in the list is because it's easier on the user.
If you have used Quickbook's Timer, that is the style of comboboxes I am going for.
Kudos to BFree for the help, but this is the solution I was looking for. The ComboBox is using a DataSet as it's source so it's not a custom source.
protected virtual void comboBoxAutoComplete_KeyPress(object sender, KeyPressEventArgs e) {
if (Char.IsControl(e.KeyChar)) {
//let it go if it's a control char such as escape, tab, backspace, enter...
return;
}
ComboBox box = ((ComboBox)sender);
//must get the selected portion only. Otherwise, we append the e.KeyChar to the AutoSuggested value (i.e. we'd never get anywhere)
string nonSelected = box.Text.Substring(0, box.Text.Length - box.SelectionLength);
string text = nonSelected + e.KeyChar;
bool matched = false;
for (int i = 0; i < box.Items.Count; i++) {
if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().StartsWith(text, true, null)) {
matched = true;
break;
}
}
//toggle the matched bool because if we set handled to true, it precent's input, and we don't want to prevent
//input if it's matched.
e.Handled = !matched;
}
This is my solution, I was having the same problem and modify your code to suit my solution using textbox instead of combobox, also to avoid a negative response after comparing the first string had to deselect the text before comparing again against autocomplet list, in this code is an AutoCompleteStringCollection shiper, I hope this solution will help
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
String text = ((TextBox)sender).Text.Substring(
0, ((TextBox)sender).SelectionStart) + e.KeyChar;
foreach(String s in this.shippers)
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()) ||
e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
return;
e.Handled = true;
}
OK, here's what I came up with. Hack? Maybe, but hey, it works. I just filled the combobox with the days of the week (hey, I needed something), and then handle the keypress event. On every key press, I check if that word matches the begining of any word in the AutoCompleteSourceCollection. If it doesn't, I set e.Handled to true, so the key doesn't get registered.
public Form5()
{
InitializeComponent();
foreach (var e in Enum.GetValues(typeof(DayOfWeek)))
{
this.comboBox1.AutoCompleteCustomSource.Add(e.ToString());
}
this.comboBox1.KeyPress += new KeyPressEventHandler(comboBox1_KeyPress);
}
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string text = this.comboBox1.Text + e.KeyChar;
e.Handled = !(this.comboBox1.AutoCompleteCustomSource.Cast<string>()
.Any(s => s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()))) && !char.IsControl(e.KeyChar);
}
EDIT: If you're on .Net 3.5 you'll need to reference System.Linq. If you're on .NET 2.0 then use this instead:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string text = this.comboBox1.Text + e.KeyChar;
foreach (string s in this.comboBox1.AutoCompleteCustomSource)
{
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()))
{
return;
}
}
e.Handled = true;
}
I know I'm about six years late but maybe this can help somebody.
private void comboBox1_Leave(object sender, EventArgs e)
{
if (comboBox1.Items.Contains(comboBox1.Text)) { MessageBox.Show("YE"); }
else { MessageBox.Show("NE"); }
OR
if (comboBox1.FindStringExact(comboBox1.Text) > -1) { MessageBox.Show("YE"); }
else { MessageBox.Show("NE"); }
}

Categories