Remove String from Text Box from back - c#

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;
}
}
}
}
}

Related

How to limit textbox to accept only specific characters

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

Removing spaces in MaskedTextBox on Leave Event - IP Address Validation

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.

Why is this code not displaying output on the textbox?

I am beginning with C#. When I run the following code and click the generate button the output does not appear in the textbox. Why is this? I am calling the function palendrome and its not updating the textbox. What am I doing wrong? Am I missing something? What do I need to fix. I don't see the error. Please help. :(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PalendromeChecker
{
public partial class Form1 : Form
{
int num;
int count;
static int result;
int setPalendromeValue;
int copyCount;
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
count = Int32.Parse(textBox2.Text);
copyCount = count;
if (!int.TryParse(textBox2.Text, out count))
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (count < 0 || count > 100)
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
public static int palendrome(int num)
{
int temp = num; ;
int r;
int rv = 0;
while (num > 0)
{
r = num % 10;
rv = rv * 10 + r;
num /= 10;
}
if (rv == temp)
{
result = temp;
return temp;
}
else
{
return 0;
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
while (copyCount != 0)
{
string resultInString = result.ToString();
textBox3.Text = resultInString;
textBox3.Visible = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
num = Int32.Parse(textBox1.Text);
//MessageBox.Show(this.textBox1.Text);
if (!int.TryParse(textBox1.Text, out num))
{
//MessageBox.Show("This is a number only field");
//return;
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (num < 0 || num > 1000000000)
{
// MessageBox.Show("Invalid Input needs to be between 0 and 1,000,000,000");
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
label4.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
int palendromeValue;
while (count != 0)
{
palendromeValue = palendrome(num);
count--;
}
}
}
}
It is not generating any input on the textbox because your function palendrome is not generating in anyway output on any of textbox1 to textbox3.
Try this:
textBox1.Text = "output"; //Whatever output you want.
If you want to show result in textBox3 the code to update it's text property should be inside button click handler, not in text changed handler.
Also while (count != 0) or while (copyCount != 0) are like infinite loops (almost). They are going to make your form unresponsive. You need to avoid those.

Why are numeric keystrokes appearing twice?

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.

c# button click increase alphabet letter

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++;
}
}

Categories