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

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?

Related

Detect keyboard input and mouse activity on a single form

I have this below form and I want to detect key-strokes and any mouse clicks on the button.
For example, if I press S on my keyboard, message will show START and keypress will display keyboard press. The same thing happen when mouse-click on START button, except that keypress will display START BTN.
Here is my button code. If I only do for button or only IsKeyDown it works fine, but when I combine both in one form, they go haywire.
private void btnStart_Click(object sender, EventArgs e)
{
lblKeypress.Text = "START BTN";
lblmessage.Text = "START";
}
Here is my Keyboard.IsKeyDown code:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Keyboard.IsKeyDown(Key.S))
{
lblKeypress.Text = "Keyboard Press";
lblmessage.Text = "START";
}
}
Please help, thanks.
try this code
private void Form1_KeyDown(object sender,
EventArgs e){
if (e.KeyData == Keys.S){
lblKeypress.Text = "Keyboard Press";
lblmessage.Text = "START";
}
}
Make sure that in your Form you set KeyPreviewProperty to TRUE
In Form1.Designer.cs
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.form_keydown);
private void form_keydown(object sender, KeyEventArgs e)
{
int keyVal = (int)e.KeyValue;
keyValue = -1;
if ((keyVal >= (int)Keys.S))
{
keyValue = (int)e.KeyValue - (int)Keys.S;
lblKeypress.Text = "Keyboard Press";
lblmessage.Text = "START";
}
}
Note:
Ensure you do not have any unrelated WPF namespaces`
(Keyboard.IsKeyDown(Key.S)) is a WPF approach, in WinForms you are better off using combination of e.KeyValue & Keys

TextBox : Modify user's input

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

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;

C# RichTextBox ReadOnly Event

I have a read only rich text box and an editable text box. The text from the read only is from the editable. They can't be viewed at the same time. When the user presses a key it hides the read only and then selects that position in the editable.
I would like it to enter the key that was pressed into the editable without playing the error "ding"
I'm thinking that an override of the read only error function would be ideal but i'm not sure what that is.
private void EditCode(object sender, KeyPressEventArgs e)
{
int cursor = txtReadOnly.SelectionStart;
tabText.SelectedIndex = 0;
ToggleView(new object(), new EventArgs());
txtEdit.SelectionStart = cursor;
txtEdit.Text.Insert(cursor, e.KeyChar.ToString());
}
Answer:
private void EditCode(object sender, KeyPressEventArgs e)
{
e.Handled = true;
int cursor = txtCleanCode.SelectionStart;
tabText.SelectedIndex = 0;
ToggleView(new object(), new EventArgs());
txtCode.Text = txtCode.Text.Insert(cursor, e.KeyChar.ToString());
txtCode.SelectionStart = cursor + 1;
}
I'll have to make it check if it's a non-control char but that's another deal. Thanks everyone!
One idea is to make the rich text box editable but canceling out all keys:
private void richtextBox1_KeyDown(object sender, KeyEventArgs e)
{
// Stop the character from being entered into the control
e.Handled = true;
// add any other code here
}
Here is one way: Check for <Enter> so the user can still use the navigation keys:
private void txtReadOnly_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true; // no ding for normal keys in the read-only!
txtEdit.SelectionStart = txtReadOnly.SelectionStart;
txtEdit.SelectionLength = txtReadOnly.SelectionLength;
}
}
No need to fiddle with a cursor. Make sure to have:
txtEdit.HideSelection = false;
and maybe also
txtReadOnly.HideSelection = false;
Obviously to keep the two synchronized :
private void txtEdit_TextChanged(object sender, EventArgs e)
{
txtReadOnly.Text = txtEdit.Text;
}
You will need o decide on some way fo r the user to return from editing to viewing. Escape should be reserved for aborting the edit! Maybe Control-Enter?

TextBox for Live Search in Windows Forms

How to create a Textbox which displays "search" in grey color when it is empty and standard behavior when user starts typing text into it?
Do it via TextBox Events Enter and Leave and Attributes:
private void textBox1_Leave(object sender, EventArgs e)
{
if(textBox1.Text.Trim().Length == 0)
{
textBox1.Text = "Search";
textBox1.ForeColor = Color.LightGray;
}
}
private void textBox1_Enter(object sender, EventArgs e)
{
textBox1.Text = string.Empty;
}
See this thread at MSDN for a possible solution: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/93a67793-6426-4d4f-be9d-a9b79725efc8

Categories