How to restirct user from entering Space in Textbox C# - c#

I want to restrict the user from entering space in textbox here in my code it simply gets the first input then check if it is space. What I want to do is in the whole text the user can't enter space in textbox
private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if ((sender as TextBox).SelectionStart == 0)
e.Handled = (e.KeyChar == (char)Keys.Space);
else
e.Handled = false;
}

you need to use textbox changed event for prevent copy paste white spaces
private void txtPassword_TextChanged(object sender, EventArgs e)
{
if (txtPassword.Text.Contains(" "))
{
txtPassword.Text = txtPassword.Text.Replace(" ", "");
txtPassword.SelectionStart = txtPassword.Text.Length;
}
}

Related

Textbox doesn't return current value in Visual C#

I'm trying to put the current integer value of a textbox immediately into an integer, but with following code it seems that I'm always 1 step behind :
private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
// Only allow numeric value
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
if (txtMemoryLocation.Text != "")
{
nLocation = int.Parse(txtMemoryLocation.Text.Trim());
}
}
I always start with a number 1 in the textbox, when I change the "1" to "10", my nLocation changes to 1, when I enter "100", nLocation becomes 10.
What is going on?
the KeyPress and KeyDown event will call before add new pressed char TextBox.Text and if e.handle is false the new char will add to TextBox.Text and TextBox.TextChanged will called. you can do this like me
Note : at first add TextChanged metod to txtMemoryLocation.TextChanged
private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar));
}
private void TextChanged(object sender,EventArgs e)
{
nLocation = int.Parse(txtMemoryLocation.Text.Trim());
}
Hook the TextChanged event instead and do your parsing there. When KeyDown, KeyPress, and KeyUp fire, the textbox still hasn't had a chance to accept the new character.
Alternatively you could including the newly pressed key my modifying your existing function like this:
private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
// Only allow numeric value
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
if (txtMemoryLocation.Text != "")
{
nLocation = int.Parse(txtMemoryLocation.Text.Trim() + e.KeyChar);
}
}

How can I enter data to Textboxes sequentially

I'm a newbee to C# and I'm trying to write code in Visual Studio. I need your help.
I want to enter numbers to 20pcs textbox in tabpage1 in form by hand held barcode scanner in C#. Cursor must go to next textbox after reading from barcode scanner. And I will check the read data with some conditions (between 2 values numbers etc) for every textbox.
I write some code but it makes code size big. I think it must be easy way I need your comment and help.
The barcode scanner reads the barcode and sends barcode number + enter code. And barcode scanner read and put number to first textbox then pass to next textbox and it repeating for all textbox - how can I do this easily?
Thanks
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox1.SelectAll();
textBox2.Focus();
e.Handled = true;
}
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.SelectAll();
textBox3.Focus();
e.Handled = true;
}
}
.
.
.
.
private void textBox20_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox20.SelectAll();
textBox1.Focus();
e.Handled = true;
}
}
The good news is that the sender object is always that control which has triggered the event. In other words the sender is a reference to one of your TextBoxs.
You can take advantage of this fact and you can have a single event handler, which could be reused for multiple events.
private void textBoxN_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBoxCurrent = sender as TextBox;
textBoxCurrent.SelectAll();
//TODO: set focus for next
e.Handled = true;
}
}
So, the next question is how to get a reference to the next TextBox?
You can use the Tag property for this.
In case of WinForms the Control object has a property called Tag.
In case of WPF the FrameworkElement object has a property called Tag.
In both cases this property is an object so we can store anything in that. If we populate that with a reference to the next TextBox then the generic handler would look like this:
private void textBoxN_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBoxCurrent = sender as TextBox;
textBoxCurrent.SelectAll();
var textBoxNext = textBoxCurrent.Tag as TextBox;
textBoxNext.Focus();
e.Handled = true;
}
}
What's left?
Populate the Tag properties
Subscribe to the KeyDown events
private void Init()
{
var textBoxes = new List<TextBox> { TextBox1, TextBox2, ..., TextBox20 };
foreach(var item in textBoxes.Select((textBox, index) => (textBox, index))
{
var nextIdx = (item.index + 1) % textBoxes.Count;
item.textBox.Tag = textBoxes[nextIdx];
item.textBox.KeyDown += textBoxN_KeyDown;
}
}
We have created an iterator here which is deconstructed into a textbox and an index of this TextBox in the textBoxes collection.
We have calculated the next TextBox index into the nextIdx. Then we have wired up everything.
here is an idea for solving
class Program
{
LinkedList<TextBox> _textBoxes;
ctor()
{
_textBoxes = new LinkedList<TextBox>();
_textBoxes.List.AddLast(textbox1);
_textBoxes.List.AddLast(textbox20);
}
private void textBox_KeyDown_justOneCommonHandle(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textboxCurrent = _textBoxes.Current;
// make sure that Value is the sender
textboxCurrent.SelectAll();
_textBoxes.MoveNext();
var textboxNext = _textBoxes.Current;
// check the end of list
textboxNext.Focus();
e.Handled = true;
}
}
}
# Peter Csala, #Ivan Stavenchuk
Thanks for your idea and help. I solved my problem as shown below
I added a main Textbox (textBox21) and used keydown event of main textbox
private void textBox21_KeyDown(object sender, KeyEventArgs e)
{
TextBox tb = new TextBox();
tb.Name = "textBox" + i.ToString();
if (e.KeyCode==Keys.Enter)
{
TextBox tbx = this.Controls.Find(tb.Name, true).FirstOrDefault() as TextBox;
tbx.Text = textBox21.Text ;
i++;
if (i>20) i=1;
textBox21.SelectAll();
}
}

C# TextBox Auto Caps Lock On

I need the following code : When I press shift key then I write small letters in my TextBox in other case I write big letters something like a “reverse” or all time pressed Caps Lock Key.
So This code and other similar is helpless because there are only one kind of letter size :
textBox1.CharacterCasing = CharacterCasing.Upper;
textBox1.CharacterCasing = CharacterCasing.Lower;
Thanks for help !
The easiest option is to change the text in the TextChanged event method. After entering a character, change its layout. But you must remember that text can be pasted / cut.
If you ignore this problem, you can use this simple example:
public partial class Form1 : Form
{
int last_len = 0;
bool char_to_lower = false;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
// save last cursor position
var select_index = textBox1.SelectionStart;
// if text not delete - change char casing
if (textBox1.Text.Length > last_len && select_index > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append(textBox1.Text.Take(select_index - 1).ToArray());
// check SHIFT and CAPS
if (char_to_lower || Control.IsKeyLocked(Keys.CapsLock))
sb.Append(textBox1.Text[select_index - 1].ToString().ToLower());
else
sb.Append(textBox1.Text[select_index - 1].ToString().ToUpper());
sb.Append(textBox1.Text.Skip(select_index).ToArray());
// insert new text in textBox
textBox1.Text = sb.ToString();
// return cursor position
textBox1.SelectionStart = select_index;
}
// save last length
last_len = textBox1.Text.Length;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Shift) char_to_lower = true;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Shift) char_to_lower = false;
}
}

Prevent printing spaces in C# TextBox

I want to make a TextBox that doesn't allow entering spaces. I disabled typing spaces with the keyboard:
void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Space)
{
e.Handled = true;
}
}
But if the user copies a string with spaces like "Hello world", he can paste it into the TextBox and there will be spaces in it.
you can add a TextChanged Event Handler for your TextBox and add below code in that TextChanged event:
TextBox1.Text = TextBox1.Text.Replace(" ", "");
A better control approach
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) {
removeSpaces();
}
//Handle Ctrl+Ins
if (e.KeyCode == Keys.Control && e.KeyCode == Keys.Insert)
{
removeSpaces();
}
}
private void removeSpaces()
{
textBox.Text = textBox.Text.Replace(" ", string.Empty);
}
// To control Mouse Right click
private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
textBox1.ContextMenu = new ContextMenu();
}
}
SIMPLE Solution for all
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Replace(" ", string.Empty);
}
A simple way is removing white space after entering data. Like:
txt_Box.Text = txt_Box.Text.Replace(" ","");

c# windows forms capital letters

My user can enter some text into the combobox but I wish that this text is automatically shown in capital letters (as if user had capslock on). Any ideas how to do this?
You will want to handle the KeyPress event.
private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
e.KeyChar -= (char)32;
}
32 is just the difference in ASCII values between lowercase and uppercase letters.
Here is how I handled it, it gives a much smoother change than simply replacing the whole text.
private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetter(e.KeyChar))
{
int p = this.SelectionStart;
this.Text = this.Text.Insert(this.SelectionStart, Char.ToUpper(e.KeyChar).ToString());
this.SelectionStart = p + 1;
}
}
another example
private void TextBox_Validated(object sender, EventArgs e)
{
this.TextBox.Text = this.TextBox.Text.ToUpper();
}
Regards
You can register to the TextChanged event and convert the text to capitals.
private void combobox_TextChanged(object sender, EventArgs e)
{
string upper = combobox.Text.ToUpper();
if(upper != combobox.Text)
combobox.Text = upper;
}

Categories

Resources