TextBox : Modify user's input - c#

When the user adds a ;, I want to add ; + Environment.NewLine in the TextBox.
I find this solution :
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text == ";")
{
e.Handled = true;
TextCompositionManager.StartComposition(
new TextComposition(InputManager.Current,
(IInputElement)sender,
";" + Environment.NewLine)
);
}
}
But after this, the undo don't work.
Can you explain me how control the user input and keep the undo stack?

-------------- Updated Code As Requested ---------
Use this Instead and 100% it's work. I test it for assurance.
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text == ";")
{
// In this line remove preview event to preventing event repeating
((TextBox)sender).PreviewTextInput -= TextBox_OnPreviewTextInput;
// Whith this code get the current index of you Caret(wher you inputed your semicolon)
int index = ((TextBox)sender).CaretIndex;
// Now do The Job in the new way( As you asked)
((TextBox)sender).Text = ((TextBox)sender).Text.Insert(index, ";\r\n");
// Give the Textbox preview Event again
((TextBox)sender).PreviewTextInput += TextBox_OnPreviewTextInput;
// Put the focus on the current index of TextBox after semicolon and newline (Updated Code & I think more optimized code)
((TextBox)sender).Select(index + 3, 0);
// Now enjoy your app
e.Handled = true;
}
}
Wish you bests , Heydar

Thank to Heydar for the solution.
I applied some improvements :
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text == ";")
{
var textBox = (TextBox) sender;
var selectStart = textBox.SelectionStart;
var insertedText = ";" + Environment.NewLine;
// In this line remove preview event to preventing event repeating
textBox.PreviewTextInput -= TextBox_OnPreviewTextInput;
// Now do The Job
textBox.Text = textBox.Text.Insert(selectStart, insertedText);
// Give the TextBox preview Event again
textBox.PreviewTextInput += TextBox_OnPreviewTextInput;
// Put the focus after the inserted text
textBox.Select(selectStart + insertedText.Length, 0);
// Now enjoy your app
e.Handled = true;
}
}

Related

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.

Validade date in PreviewTextInput DatePicker

I have a DatePicker and a problem in PreviewTextInput event.
I need to include the "/" digit when length is 2 for days and 4 for months.
So, after input goes to 12 for example, i need to include "/" to keep "12/", but if i do that, the text reset and goes for another date.
private void dpDataEmissao_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if ((dpDataEmissao.Text + e.Text).Length == 2)
dpDataEmissao.Text += e.Text + "/";
if ((dpDataEmissao.Text + e.Text).Length == 4)
dpDataEmissao.Text += e.Text + "/";
}
The final result must be: "12/04/2017" and user need only put "12042017" and "/" will be included automatically.
Someone already get this problem ?
Using a TextBox:
You need to set e.Handled to true an adjust the position of the cursor:
if ((dpDataEmissao.Text + e.Text).Length == 2)
{
e.Handled = true;
dpDataEmissao.Text += e.Text + "/";
}
if ((dpDataEmissao.Text + e.Text).Length == 5)
{
e.Handled = true;
dpDataEmissao.Text += e.Text + "/";
}
if (e.Handled)
{
dpDataEmissao.CaretIndex = dpDataEmissao.Text.Length;
}
Using DatePicker: (Not that nice)
private void dpDataEmissao_KeyUp(object sender, KeyEventArgs e)
{
if (new int[] { 2, 5 }.Contains(dpDataEmissao.Text.Length))
{
InputSimulator.SimulateTextEntry("/");
}
}
InputSimulator is part of: Windows Input Simulator
PS:
Don't forget to change the 4 to 5!

How to disable button if textbox is empty

First of all sorry for my bad english.
I'm beginner at C# and i made a Windows forms application but i can't disable one button if a textbox is empty.
I tried some of the Enabled methods but they didn't work. Hope someone can help me fix this. Thank you very much
public partial class ModulusForm : Form
{
public double nje;
public double dy;
public double pergjigja;
public double rezultati;
public ModulusForm()
{
InitializeComponent();
Button btn = new Button();
btn.Click += new EventHandler(butoniGjenero_Click);
}
private void butoniPerfundo_Click(object sender, EventArgs e)
{
this.Close();
}
private void butoniGjenero_Click(object sender, EventArgs e)
{
Random random = new Random();
nje = random.Next(1, 100);
dy = random.Next(1, 100);
if (nje > dy)
{ textboxPyetja.Text = "X = " + nje + " " + "dhe" + " " + "Y = " + dy; }
else if (nje > dy)
{
nje = random.Next(1, 100);
dy = random.Next(1, 100);
}
rezultati = nje / dy;
}
private void butoniPastro_Click(object sender, EventArgs e)
{
textboxPyetja.Clear();
textboxPergjigja.Clear();
textboxPergjigjaSakt.Clear();
}
private void butoniVerteto_Click(object sender, EventArgs e)
{
try
{
pergjigja = double.Parse(textboxPergjigja.Text);
}
catch
{
var informim = MessageBox.Show("Rishiko fushat!", "Verejtje", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (textboxPergjigja.Text == "")
{
//nothin' baby
}
else
{
if (textboxPyetja.Text == "")
{
var informim = MessageBox.Show("Fusha e pyetjes eshte null!", "Verejtje", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (pergjigja == rezultati)
{
textboxPergjigjaSakt.Text = "Pergjigja eshte e sakte";
}
else
{
textboxPergjigjaSakt.Text = "Gabim." + " " + "Pergjigja e sakte eshte: " + "" + rezultati;
}
comboboxVargu.Items.Add(nje + " / " + dy + " = " + rezultati);
}
}
}
}
}
Credit to #Cody Gray for already suggesting this; I have just expanded it, so you can see how to implement and how it works
Overview
You can wire up an event handler for when your textboxPergjigja.Text's text has changed.
In the handler you create, you can then evaluate whether your button should be Enabled or not - using the string.IsNullOrWhiteSpace() check to set this.
First:
In your constructor for the form, subscribe to the textboxPergjigja.Text text box's TextChanged event.
Like this:
public ModulusForm()
{
InitializeComponent();
Button btn = new Button();
btn.Click += new EventHandler(butoniGjenero_Click);
// Add the subscription to the event:
textboxPergjigja.TextChanged += textboxPergjigja_TextChanged;
}
Next:
Add a handler that matches the correct delegate signature for that event.
Like this:
public textboxPergjigja_TextChanged(object sender, TextChangedEventArgs e)
{
// If the text box is not "empty", it will be enabled;
// If the text is "empty", it will be disabled.
butoniVerteto.Enabled = !string.IsNullOrWhiteSpace(textBoxPergjigja.Text);
}
This way, whenever the text in the textBoxPergjigja text box is changed; the evaluation is run and your button will always be enabled/disabled correctly.
Hope this helps! :)
Additional Info
You can also use textBox.Text.IsNullOrEmpty(), and it will still work - as suggested by #Cody
I have used string.IsNullOrWhiteSpace(), as opposed to textBox.Text.IsNullOrEmpty() for the following reasons:
The .IsNullOrEmpty() method only checks if the textBox.Text is either null or the total amount of characters is equal to 0.
The problem this might pose is, if the user only enters a space in the textbox, it is no longer Empty or null; thus this check will return true. If the logic of the program requires that an actual value be entered into the textbox, this logic can be flawed.
On the other hand: The string.IsNullOrWhiteSpace() check will check on 3 conditions - if the input string is null, Empty and contains only whitespace characters (space, newline etc.), also.
I hope this adds a little bit of extra fluff to give you an informed decision for future.
Hope it work!
private void YourTextBox_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(YourTextBox.Text))
YourButton.Enabled = false;
else
YourButton.Enabled = true;
}
Handle it on TextChanged event of your TextBox. (double click on your textbox control when in designed, which will automatically create the text changed event for you).
private void textboxPyetja_OnTextChanged(..blah blah)
{
if(String.IsNullOrWhitespace(txtTargetTextbox.Text)
{
//disable your control
}
else
{
//enable your control
}
}
Edit after 4 years - for some reason:
And here's a one-liner version, some people just love them...
private void textboxPyetja_OnTextChanged(..blah blah)
{
btnILoveButtons.Enabled = string.IsNullOrWhitespace(txtTargetTextbox.Text);
{
Try this:
if (String.IsNullOrEmpty(textboxPergjigja.Text))
butoniVerteto.Enabled = false;
else
butoniVerteto.Enabled = true;
add an event for edit text in the txtbox. when the text changes, enable the button
Change textBox1 for your textbox name then change button1 name for you button name
if (textBox1.Text == "")
{
button1.Enabled = false;
}
else
button1.Enabled = true;

How to use multiline textbox in order to use list item

I want to use a textbox which has multiline (TextMode = TextBoxMode.MultiLine) property.
But while writing any line in to textbox when I write like below (sample1), I want to show a list item icon like sample2.
(sample1)
Stack
Over
StackOver
StackOverflow
(sample2)
* Stack
* Over
* StackOver
* StackOverflow
Is it possible?
This might not be the most elegant way but it works for me. Use the Key_Up event and catch the Return key :
private void TextBox1_KeyUp(System.Object sender, System.Windows.Forms.KeyEventArgs e) {
if (e.KeyCode == Keys.Return) {
string[] TextLines = TextBox1.Text.Split(Environment.NewLine);
TextBox1.Text = "";
foreach ( txLine in TextLines) {
if (!txLine.Contains("*") & !string.IsNullOrEmpty(txLine.Trim)) {
txLine = "* " + txLine;
}
TextBox1.Text += (txLine + Environment.NewLine);
}
TextBox1.SelectionStart = TextBox1.Text.Length;
TextBox1.ScrollToCaret();
}
}
Note That you will get an empty line in between the lines, I'll let you fix it :-)

Cancel/Clear button event Post Back And Trying To Validate Fields

this is driving me crazy.
I have a piece of code on a Windows Form Control, this code ensures the form clears and put the focus back to the first Control (Phone Number). The problem is I am using On-Leave Event Handles and this handler contain the Validation code so that the Phone is validated when the use leaves the control.
When I hit Reset or Exit of the form, it not only clears the form, it also sends the focus back to the Phone field, causing the control (Textbox) to Validate.
I need the focus on the Phone control with at the validation on focus, is there a way I can prevent this behavior?
private void txtPhone_Leave(object sender, EventArgs e)
{
Int64 ConvertPhone;
if (txtPhone.Text.Trim().Length != 10)
{
lblPhoneError.Visible = true;
lblErrorIndicator.Visible = true;
lblErrorIndicator.Text = "*Valid 10 digit phone number required";
}
else if (Int64.TryParse(txtPhone.Text, out ConvertPhone))
{
lblPhoneError.Visible = false;
lblErrorIndicator.Visible = false;
txtPhone.MaxLength = 10;
txtPhone.Text = txtPhone.Text.Substring(0, 3) + "." + txtPhone.Text.Substring(3, 3) + "." + txtPhone.Text.Substring(6, 4);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtPhone.Clear();
txtPhone.Focus();
}
private void txtPhone_Enter(object sender, EventArgs e)
{
txtPhone.Text = txtPhone.Text.Replace(".", "");
}
Thanks everyone!
if (txtPhone.Text.Trim().Length != 10)
{
if (txtPhone.Text != "")
{
lblErrorIndicator.Visible = true;
lblErrorIndicator.Text = "*Valid 10 digit phone number required";
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtPhone.Clear();
lblErrorIndicator.Text="";
txtPhone.Focus();
}
I can understand your problem but tell me what you want to do at the end?

Categories