I'm trying to do IPv4 validation in a maskedtextbox. My mask is set to ###.###.###.### and i have my Key Down Event handling the '.' key as going to next octet which works great... However, if an IP address dows not have 3 digits in each octet i get random spaces when I grab the textfield for use.
For example: if I type 72.13.12.1 the output is "72 .13 .12 .1" <- I don't want the spaces.
I've tried doing some validation like removing the spaces once I leave the maskedtextbox, but if I remove the spaces, my mask kicks back in and changes it to "721.321.1 ."
this.maskedTextBoxExternIP.ResetOnSpace = false;
this.maskedTextBoxExternIP.SkipLiterals = false;
this.maskedTextBoxExternIP.PromptChar = ' ';
this.maskedTextBoxExternIP.Mask = "###.###.###.###";
this.maskedTextBoxExternIP.ValidatingType = typeof(System.Net.IPAddress);
this.maskedTextBoxExternIP.KeyDown += new KeyEventHandler(this.maskedTextBoxExternIP_KeyDown);
this.maskedTextBoxExternIP.Enter += new EventHandler(this.maskedTextBoxExternIP_Enter);
this.maskedTextBoxExternIP.Leave += new EventHandler(this.maskedTextBoxExternIP_Leave);
private void maskedTextBoxExternIP_Leave(object sender, EventArgs e)
{
// Resets the cursor when we leave the textbox
maskedTextBoxExternIP.SelectionStart = 0;
// Enable the TabStop property so we can cycle through the form controls again
foreach (Control c in this.Controls)
c.TabStop = true;
IPAddress ipAddress;
if (IPAddress.TryParse(maskedTextBoxExternIP.Text, out ipAddress))
{
//valid ip
}
else
{
//is not valid ip
maskedTextBoxExternIP.Text = maskedTextBoxExternIP.Text.Replace(" ", string.Empty);
}
}
// Handle the Enter event
private void maskedTextBoxExternIP_Enter(object sender, EventArgs e)
{
// Resets the cursor when we enter the textbox
maskedTextBoxExternIP.SelectionStart = 0;
// Disable the TabStop property to prevent the form and its controls to catch the Tab key
foreach (Control c in this.Controls)
c.TabStop = false;
}
// Handle the KeyDown event
private void maskedTextBoxExternIP_KeyDown(object sender, KeyEventArgs e)
{
// Cycle through the mask fields
if (e.KeyCode == Keys.Tab || e.KeyCode == Keys.OemPeriod || e.KeyCode == Keys.Decimal)
{
int pos = maskedTextBoxExternIP.SelectionStart;
int max = (maskedTextBoxExternIP.MaskedTextProvider.Length - maskedTextBoxExternIP.MaskedTextProvider.EditPositionCount);
int nextField = 0;
for (int i = 0; i < maskedTextBoxExternIP.MaskedTextProvider.Length; i++)
{
if (!maskedTextBoxExternIP.MaskedTextProvider.IsEditPosition(i) && (pos + max) >= i)
nextField = i;
}
nextField += 1;
// We're done, enable the TabStop property again
if (pos == nextField)
maskedTextBoxExternIP_Leave(this, e);
maskedTextBoxExternIP.SelectionStart = nextField;
}
}
#madreflection I finally got the IPAddressCrontrolLib to work I just used the source files and embedded the library that way. Had to do a little fudging around to clear all the errors that we there. All good now! Just needed a new day to get through that one. Thanks for your help.
Related
I wanted to know How to limit number of specific character of a textbox in c# form application.
for example i want to limit the user to enter - (minus) only one time and then if he try to input again I want the program to restrict inputing that again.
Examples: -123 or 123- or 123-123 (only one -).
If user remove - then should have permission to input one - again and of course no more!
I want to prevent user to enter ----1234 or 1234--, or 123-4--21 or what more you think!!
Here is what I'm trying:
private void txtStopAfterXTimes_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract)
{
if (txtStopAfterXTimes.Text.Count((char)'-', 1))
{
e.SuppressKeyPress = true;
}
else if (txtStopAfterXTimes.Text.Count((char)'-', 0))
{
e.SuppressKeyPress = false;
}
}
}
i know it's wrong but please help!
thank you...
You can change the Text within txtStopAfterXTimes by 2 ways: pressing a key (-) or by pasting a value.
That's why we have to handle 2 events: KeyPress for - key pressing and TextChanged for text pasting:
Code: (WinForms)
private void txtStopAfterXTimes_TextChanged(object sender, EventArgs e) {
// When pasting a text into txtStopAfterXTimes...
TextBox box = sender as TextBox;
StringBuilder sb = new StringBuilder(box.Text.Length);
bool containsMinus = false;
// We remove all '-' but the very first one
foreach (char ch in box.Text) {
if (ch == '-') {
if (containsMinus)
continue;
containsMinus = true;
}
sb.Append(ch);
}
box.Text = sb.ToString();
}
private void txtStopAfterXTimes_KeyPress(object sender, KeyPressEventArgs e) {
TextBox box = sender as TextBox;
// we allow all characters ...
e.Handled = e.KeyChar == '-' && // except '-'
box.Text.Contains('-') && // when we have '-' within Text
!box.SelectedText.Contains('-'); // and we are not going to remove it
}
I'd avoid using TextChanged because it will be raised after the text has changed and it may be a bit late.
This is the solution which I will use, because you also need to care about paste.
On keyPress I check if the character is not the first "-", then I'll ignore it, otherwise I'll accept it.
On WndProc I catch WM_PASTE and sanitize the clipboard text, by removing all occurrences of "-" but the first one. You can also easily decide to stop pasting if the input is not acceptable.
Here is the implementation:
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class MyTextBox : TextBox
{
private const int WM_PASTE = 0x0302;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool MessageBeep(int type);
protected override void WndProc(ref Message m)
{
if (m.Msg != WM_PASTE) { base.WndProc(ref m); }
else {
//You can sanitize the input or even stop pasting the input
var text = SanitizeText(Clipboard.GetText());
SelectedText = text;
}
}
protected virtual string SanitizeText(string value)
{
if (Text.IndexOf('-') >= 0) { return value.Replace("-", ""); }
else {
var str = value.Substring(0, value.IndexOf("-") + 1);
return str + value.Substring(str.Length).Replace("-", "");
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '-' && this.Text.IndexOf('-') >= 0) {
e.Handled = true;
MessageBeep(0);
}
else {
base.OnKeyPress(e);
}
}
}
I'm new to C#. Using the code below, whenever I press a number key on my keyboard, it will display twice in the textbox. When I press "1" on the keyboard it will display
"11", and when I press "2" it will display "22". Why is this?
private void Window_TextInput(object sender, TextCompositionEventArgs e)
{
if(!isNumeric(e.Text))
{
string display = string.Empty;
display += e.Text;
displayNum(display);
}
else
{
String inputOperator = string.Empty;
inputOperator += e.Text;
if (inputOperator.Equals("+"))
{
ApplySign(sign.addition, "+");
}
}
}
private bool isNumeric(string str)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
return reg.IsMatch(str);
}
private void window_keyUp(object sender, KeyEventArgs e)
{
if (e.Key >= Key.D0 && e.Key <= Key.D9)
{
int num = e.Key - Key.D0;
outputText2.Text += num;
}
}
private void BtnNum_Click(object sender, RoutedEventArgs e)
{
Button num = ((Button)sender);
displayNum(num.Content.ToString());
}
private void displayNum(String n)
{
if (operator1 == 0 && double.Parse(n) == 0)
{
}
else
{
if (operator1 == 0)
{
outputText2.Clear();
}
outputText2.Text += n;
operator1 = double.Parse(outputText2.Text);
outputText2.Text = Convert.ToString(operator1);
}
}
You have two events that are handeling the Keyboard events. Although not really sure what the displayNum() method is doing
I am assuming the Window_TextInput event is the event you wish to primarily handle the event.
Try adding
e.Handled = true;
In the Window_TextInput method. If that doesn't solve the problem can you post the displayNum() method?
EDIT:
After further review of the code and trying the same I do not see the relevance for the window_keyUp method as your Window_TextInput handles the input characters and has more applicable logic for handling the TextInput changes.
After I removed the window_keyUp event method the output appeared as expected (although commented out the ApplySign() method.
You've subscribed to two window-level text-related events - TextInput and KeyUp - and both of them end up appending input to the TextBox.
window_keyUp appends numbers to the TextBox
It looks like Window_TextInput is supposed to append non-numeric characters, but your RegEx is incorrect ([^0-9] matches anything that is not numeric, so IsNumeric returns True if the input is not a number)
The effect is that every numeric key press shows up twice.
I have a button on a c# form that when it is clicked, should change its text value to the next letter in the alphabet sequence.
The default button value is a dash "-" (when the application starts). When the button is clicked, it should change to A, and when it's click again, change to B. At Z, it should reset to A.
I have the following code, however, when the button is pressed, it just returns an open bracket "[".
private void alphaCode_Click(object sender, EventArgs e)
{
string s = null;
for (char c2 = 'A'; c2 <= 'Z' + 1; c2++)
{
s = c2.ToString();
}
alphaCode.Text = s;
}
You do not need a loop in the alphaCode_Click, because the cycle happens outside of the "on click" event handler. It's the user who does the looping (by clicking a button); your code performs a single step of that loop.
Therefore, all you need is to pick the letter from the alphaCode.Text, add one to it, and set it back into the alphaCode.Text field:
private void alphaCode_Click(object sender, EventArgs e)
{
string s = null;
var current = alphaCode.Text.Length == 1 ? alphaCode.Text[0] : 'A';
if (current >= 'A' && current <= 'Z') {
current++;
} else {
current = 'A';
}
alphaCode.Text = "" + current;
}
A solution that does not depend on the current text value and works for any alphabet:
string const Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int _currentCharacterIndex = -1;
private void alphaCode_Click(object sender, EventArgs e)
{
_currentCharacterIndex = (_currentCharacterIndex +1) % Alphabet.Count;
alphaCode.Text = Alphabet[_currentCharacterIndex ];
}
(Untested. I don't have access to Visual Studio right now.)
You are enumerating through all the letters as soon as the button is pressed. Basically, you only want to advance your character once per press.
private void alphaCode_Click(object sender, EventArgs e)
{
char currentChar = alphaCode.Text[0];
if(currentChar == '-')
{
alphaCode.Text = "A";
}
else
{
char newChar = currentChar + 1;
if(newChar > 'Z')
{
newChar = 'A';
}
alphaCode.Text = newChar;
}
}
Use the ASCII code of current text as tag for the button. On each click, increase it and change the text. Now, once you have moved through the range (Z that is), reset to a.
Are you dealing with both uppercase and lowercase?
private void alphaCode_Click(object sender, EventArgs e)
{
char s = Convert.ToChar(alphaCode.Text.Trim());
if (s == '-' || s == 'Z')
{
alphaCode.Text = "A";
}
else
{
s++;
alphaCode.Text = s.ToString();
}
}
The char Z is the 90th (dec) in the ASCII table, so when you loop until 90 + 1 = 91, and assign the textBox to it, it shows '[' which is the 91th. For the sake of simplicity, have a char created as a field (within the class, not any function or procedure), and everytime the user clicks you just assign the textbox to the current value and then increment it.
private void alphaCode_Click(object sender, EventArgs e)
{
txtAlph.Text = currentChar.ToString();
currentChar++;
}
Then, as a field, just use a char to hold the value:
char currentChar = 'A';
Set your char as an field. And increase the value of c with every buttonclick. If c = Z then start again on A...
char c = 'A';
private void button_Click(object sender, EventArgs e) {
if(c == 'Z'){
c = 'A';
}
label1.Text = c + "";
c++;
}
Just loop through the char code
public partial class Form1 : Form
{
private int _charCode = 65;
public Form1()
{
InitializeComponent();
alphaCode.Text = "-";
}
private void alphaCode_Click(object sender, EventArgs e)
{
// 90 is 'Z'
if (_charCode > 90)
_charCode = 65;
alphaCode.Text = ((char)_charCode).ToString();
_charCode++;
}
}
I have a requirement in C# where I have a text box with numbers delimited by ; say e.g.
(205)33344455;918845566778;
Now when a user presses ← Backspace (to remove the number) one character at a time gets deleted. I want to delete the whole number at once.
So when the user presses ← the first time, the number will be highlighted
i.e. if text is (205)33344455;918845566778;, the 918845566778; part will be highlighted in say black, and when the user presses ← again the whole number i.e. 918845566778; will be deleted.
So is it possible to highlight a particular section in text box, and delete the whole number?
I used a for loop like:
for{back=txtPhone.Text.Length;back<=txtPhone.Text.indexOf(';');back--)
But I was not able to achieve the desired result.
Any help on this would be great.
You can implement your requirement as shown below
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.Text.Length == 0) return;
if ((e.KeyChar == (char)Keys.Back) && (textBox1.SelectionLength == 0))
{
textBox1.SelectionStart = Math.Max(0, textBox1.Text.Substring(0,textBox1.Text.Length-1).LastIndexOf(';'));
if (textBox1.Text.Substring(textBox1.SelectionStart, 1) == ";") textBox1.SelectionStart++;
textBox1.SelectionLength = textBox1.Text.Length-textBox1.SelectionStart ;
e.Handled = true;
return;
}
if ((e.KeyChar == (char)Keys.Back) && textBox1.SelectionLength >= 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.SelectionStart );
textBox1.SelectionStart = textBox1.Text.Length;
e.Handled = true;
}
}
A couple of methods to achieve want you want come to mind:
Subscribing the text box to Control.Keydown event which would check for the ← button and perform the highlight up to the last delimiter (;) using TextBox.SelectionLength meaning a ← Backspace will clear it.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Left)
return;
e.SuppressKeyPress = true;
//Select up to previous delimeter (;) here
}
Use a listbox (or something similar) to store the delimited data as it is entered. This will allow the user to select what they need, and remove it via a button you will provide.
You can :
Select the token (i.e. number terminated by ;) that contains the cursor (method selectToken())
Remove it when backspace is
pressed a second time
Example:
your textbox contains '(205)33344455; 918845566778; 8885554443;'
you click with the left mouse button between 9188455 and 66778; (second number)
then you press backspace
the string 918845566778; gets selected
you press backspace a second time and that string gets deleted
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Remove_String_from_Text_Box_from_back
{
public partial class Form1 : Form
{
//selects token that contains caret/cursor
private void selectToken() {
string str0 = textBox1.Text;
int caretPosition = textBox1.SelectionStart;
int tokenEndsAtIndex = str0.IndexOf(';', caretPosition, (textBox1.Text.Length - caretPosition));
string prefix = "";
if (tokenEndsAtIndex == -1)
{
tokenEndsAtIndex = str0.IndexOf(';');
}
prefix = str0.Substring(0, tokenEndsAtIndex);
int tokenStartsAtIndex = 0;
tokenStartsAtIndex = prefix.LastIndexOf(';');
if (!(tokenStartsAtIndex > -1)) { tokenStartsAtIndex = 0; } else { tokenStartsAtIndex++; }
textBox1.SelectionStart = tokenStartsAtIndex;
textBox1.SelectionLength = tokenEndsAtIndex - tokenStartsAtIndex + 1;//may be off by one
}
private void selectLastToken(string str0)
{
Regex regex = new Regex(#"([\d()]*;)$");
var capturedGroups = regex.Match(str0);
int idx0 = 0;
if (capturedGroups.Captures.Count > 0)
{
idx0 = str0.IndexOf(capturedGroups.Captures[0].Value, 0);
textBox1.Select(idx0, textBox1.Text.Length);
}
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "(205)33344455;918845566778;";
textBox1.Select(0, 0);
}
//selects last token terminated by ;
private void selectTextOnBackSpace()
{
string str0 = textBox1.Text;
int idx0 = str0.LastIndexOf(';');
if (idx0<0)
{
idx0 = 0;
}
string str1 = str0.Remove(idx0);
int idx1 = str1.LastIndexOf(';');
if (idx1 < 0)
{
idx1 = 0;
}
else
{
idx1 += 1;
}
textBox1.SelectionStart = idx1;
textBox1.SelectionLength = str0.Length - idx1;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back )
{
if (textBox1.SelectionLength==0)
{
selectToken();
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}
}
}
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"); }
}