In TextBox_Leave event i need to check whether numbers entered in textbox is in serial number or not.If it is not in order then i need to display a message as "number" is missing
For example :
In textbox i have entered 3 and click tab :
I need to display message as
"Number is not in order , number "1" and "2" is missing "
I don't know whether this also works in c#2.0, this is my experience in c#3.0:
Why do you use TextBox_Leave for that? The Validating-event should be used for validating whether input is correct.
Combine using the Validating-event with using an ErrorProvider (you can just drag it from the toolbox onto the form) to set an error message: it will be displayed as a (blinking) exclamation mark in a red triangle.
An ErrorProvider can also block any submit-actions.
One trick is to retain focus in the textbox when trying to leave (with TAB for instance) in case of some condition (missing number):
private void textBox1_Leave(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb.Text == "3")
tb.Focus();
}
Assuming you are using a standard textbox. You could also use third party controls that where you can cancel an event (e.Cancel = true) on some condition.
Try using a Masked TextBox control and set a custom property for this type of field validation.
Alternatively you can also use Validating event of the text box.
private void textBox1_Validating( object sender, CancelEventArgs e )
{
if ( textBox1.Text == "3" )
e.Cancel = true;
}
The text-box wont loose focus until it receives a valid input.
I will show you how to validate Validating WinForms TextBox (in C#).
Create a function:
public static void ChkBlankTextBoxes(object sender, string type)
{
if (sender is TextBox)
{
TextBox textbox = sender as TextBox;
if (string.IsNullOrEmpty(textbox.Text))
{
MessageBox.Show("Please enter correct value value..");
textbox.Focus();
}
}
}
Call to created function:
ChkBlankTextBoxes(txt_userID, textBoxtype);
ChkBlankTextBoxes(txt_password, textBoxtype);
Related
I am building a simple calculator. I have three textBoxes: textBox1 (first operand), textBox2 (second operand), and textBox3 (result). I have numerous operand functions that can be performed. I also have a button that will clear all fields, as well as other functions.
I am having difficulty with the code needed to delete the text in a specific textbox with a button only when the cursor is in that textbox.
Ex: if cursor is in textBox1, the button only clears that textbox.
Any help is much appreciated.
Thanks.
When the Button is clicked it will gain focus.
So you need to keep track of which of your TextBoxes got focus last.
Create a class level variable for that:
TextBox focusedTextBox = null;
Now hook up this event with the Enter event of all three TextBoxes:
private void textBoxes_Enter(object sender, EventArgs e)
{
focusedTextBox = sender as TextBox;
}
Then this will only clear the one your user was in last:
private void buttonClearCurrent_Click(object sender, EventArgs e)
{
if (focusedTextBox != null) focusedTextBox.Text = "";
}
In this case you have to use the Focused property in the textbox.
But you need to make a loop to identify which text box is focused.
like:
var focusedControl;
foreach(var control in this.Controls)
{
if(control is TextBox)
{
if(control.Focused)
{
focusedControl = control;
break;
}
}
}
You can use event: "MouseHover" or "MouseClick" and set textBox1.Text=""
I have code using an AutoCompleteStringCollection:
private void txtS_TextChanged(object sender, EventArgs e)
{
TextBox t = sender as TextBox;
string[] arr = this.dbService.GetAll();
if (t != null)
{
if (t.Text.Length >= 3)
{
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
collection.AddRange(arr);
this.txtSerial.AutoCompleteCustomSource = collection;
}
}
}
How can I get the event for "item selected" after user selects an AutoComplete suggestion? And value of field?
There's no such thing as chosen item Event for a textBox, which I believe you're using for the AutoComplete. What you could do is add a key down event to your textBox. There you could verify if the enter key was pressed (clicking on a suggested link is the same as pressing enter). Something like that:
private void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == Keys.Enter) {
String selItem = this.textBox1.Text;
}
}
Rather than focusing on detecting if an item from the autocomplete list was selected, instead you should check if the current value of the textbox is in the set of autocomplete entries.
if (txtSerial.AutoCompleteCustomSource.Contains(t.Text))
{
// Logic to handle an exact match being selected
...
}
else
{
// Update the autocomplete entries based on what was typed in
}
If the user typed in an exact string which happens to be be within the list of autocomplete values -- OR -- they select that value from the autocomplete list -- should this produce any different behavior? I think that in most cases it should not.
Short answer: make a custom event
Long answer:
You can intercept the KeyDown event of your textbox for numpad Enter or normal Enter and the mouse doubleclick event of the toolbox and compare the content of the toolbox then fire an event if they match that a delegate will pick up.
It depends a bit on the situation and workflow of your program but I have an example where I trigger the check on focuslost of the combobox. And then I check if the selected value is part of the collection:
private void cmbt1Name1_LostFocus(object sender, RoutedEventArgs e)
{
ComboBox cmb = sender as ComboBox;
FillFivePoints(cmb);
}
private void FillFivePoints(ComboBox usedCombobox)
{
if (txtSerial.AutoCompleteCustomSource.Contains(t.Text))
{
...
I am trying to make the save button visible when text is entered into the text box by using the following code:
if (tbName.TextModified == true)
{
btnCTimetablesOk.Visible = true;
}
else
{
btnCTimetablesOk.Visible = false;
}
but it gives error at tbname.textmodified
is there any other way to visible the button when we enter the text in text box
this is error i am getting "the event textbox.textmodified can only appear on the left hand side of += or -="
Try using the textbox's Enter and Leave events to show/hide your button:
private void textBox1_Enter(object sender, System.EventArgs e)
{
btnCTimetablesOk.Visible = true;
}
private void textBox1_Leave(object sender, System.EventArgs e)
{
btnCTimetablesOk.Visible = false;
}
Then modify your textbox to use these new methods.
If I'm reading your text correctly, you want the save button to be visible when the textbox has text in it and invisible when the text box is blank. If that's the case, you can use the Leave event (which occurs when the textbox loses focus) and a simple if statement:
private void textBox1_Leave(object sender, System.EventArgs e)
{
if(textBox1.Text != "")
btnCTimetablesOk.Visible = true;
else
btnCTimetablesOk.Visible = false;
}
You can also put this conditional block in any other methods kicked off by events that change the text of the box.
Also, you might want to consider using Enabled instead of Visible, it'll leave the button on the form but will gray out the text and clicking will do nothing.
I'm going to take a stab in the dark here and assume that the button is related to the textbox and you probably want someone to be able to type something in the textbox then click the button. You probably don't want the user to have to type something, then tab out or click somewhere else to make the button visible then click the button.
tbName_TextChanged(object sender, EventArgs e)
{
btnCTimetablesOk.Visible = !String.IsNullOrEmpty(tbName.Text)
}
Btw you're getting that error because TextModified isn't a boolean property, it's an event, like TextChanged or Leave or Enter. You can assign an event handler to it but you can't just check it like that.
As an aside I personally hate systems hungarian for winforms controls. I'd much rather have a timetablesOkButton than a btnCTimeablesOK button. That way if you also have a timetablesNameTextBox you can see at a glance that the button and the textbox match. Of course it may not be up to you.
I am using c# winform.
I have 2dimensional array of text boxes I want them to accept only Letters from A-I I've created the method but that works for only one text box.
Here is my code:
textbox[i,j].Validated+=new EventHandler(TextBox_KeyPress);
private void TextBox_KeyPress(object sender, EventArgs e)
{
bool bTest = txtRegExStringIsValid(textbox[1,1].Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false)
{
tip.Show("Only A-I", textbox[1,1], 2000);
textbox[1,1].Text = " ";
}
}
private bool txtRegExStringIsValid(string textToValidate)
{
Regex TheRegExpression;
string TheTextToValidate;
string TheRegExTest = #"^[A-I ]+$";
TheTextToValidate = textToValidate;
TheRegExpression = new Regex(TheRegExTest);
if (TheRegExpression.IsMatch(TheTextToValidate))
{
return true;
}
else
{
return false;
}
}
Can anyone please guide what should I do make this code work for all text boxes?
if this works for textbox[1,1] you could register your private void TextBox_KeyPress(object sender, EventArgs e) as eventhandler for all your textboxes and instead of textbox[1,1] you could use ((TextBox)sender)
i want text boxes to accept only letters from a-i actually i am trying to make sudoku
There's a much simpler solution than regular expressions, and you don't even need to handle the Validated event to implement it.
In a situation like this, where there are only certain characters that you want to prevent the user from entering, handling the KeyDown event is a much better solution. The user gets immediate feedback that the letter they tried to enter was not accepted. The alternative (the Validating and Validated events) actually wait until the user tries to leave the textbox to rudely alert them that their input was invalid. Especially for a game, this tends to break concentration and isn't particularly user-friendly.
Doing it this way also makes it irrelevant which individual textbox raised the event. Instead, you will handle it the same way for all of the textboxes—by completely ignoring all invalid input.
Here's what I'd do:
First, attach a handler method to your textbox's KeyDown event. You can do this from the Properties window in the designer, or you can do it through code, as you have in the question:
textbox[i,j].KeyDown += TextBox_KeyDown;
Then, you need to put the logic into your event handler method that determines if the key that the user just pressed is in the allowed range (A through I), or outside of it:
private void TextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Determine if the keystroke was a letter between A and I
if (e.KeyCode < Keys.A || e.KeyCode > Keys.I)
{
// But allow through the backspace key,
// so they can correct their mistakes!
if (e.KeyCode != Keys.Back)
{
// Now we've caught them! An invalid key was pressed.
// Handle it by beeping at the user, and ignoring the key event.
System.Media.SystemSounds.Beep.Play();
e.SuppressKeyPress = true;
}
}
}
If you want to restrict the user to typing in only one letter, you can add code to handle that in the above method, or you can take an even simpler route and let the textbox control handle it for you automatically. To do that, set the MaxLength property of the textbox to true, either in the designer or through code:
textbox[i,j].MaxLength = true;
Check the text of the sender instead of whatever textbox[1,1] is.
Use the sender parameter of the event handler to identify the textbox responsible for the event.
The first thing that will help you is casting the sender of your event to a TextBox like this:
(Also, as Cody Gray said, this is a TextBox_Validated event, not a KeyPress event so I've renamed it appropriately)
private void TextBox_Validated(object sender, EventArgs e)
{
TextBox tb = sender as TextBox()
if (sender == null)
return;
bool bTest = txtRegExStringIsValid(tb.Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false) {
tip.Show("Only A-I", tb, 2000);
tb .ext = " ";
}
Next you need to actually get into that code for every textbox. There are two obvious approaches to that, you can either assign the eventhandler to each textbox in the array or you can use a custom textbox which always does this validation and then add that to your array.
Assign eventhandler to textboxes
foreach(var tb in textbox)
{
tb.Validated += new EventHandler(TextBox_KeyPress);
}
Create custom textbox control
Create the custom text box control (Add a user control to the project) and then just use it exactly as you would a normal textbox.
public partial class ValidatingTextBox: TextBox
{
public ValidatingTextBox()
{
InitializeComponent();
}
protected override void OnValidating(CancelEventArgs e)
{
bool bTest = txtRegExStringIsValid(this.Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false)
{
tip.Show("Only A-I", this, 2000);
this.Text = " ";
}
}
private bool txtRegExStringIsValid(string textToValidate)
{
// Exactly the same validation logic as in the same method on the form
}
}
I have prevented numbers from being typed in text box using key down event. But when using Ctrl+V or pasting content through mouse, the numbers are being entered in the text box. How to prevent this? I have to allow all text to be pasted/typed except numbers.
On quite simple approach would be to check the text using the TextChanged event. If the text is valid, store a copy of it in a string variable. If it is not valid, show a message and then restore the text from the variable:
string _latestValidText = string.Empty;
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox target = sender as TextBox;
if (ContainsNumber(target.Text))
{
// display alert and reset text
MessageBox.Show("The text may not contain any numbers.");
target.Text = _latestValidText;
}
else
{
_latestValidText = target.Text;
}
}
private static bool ContainsNumber(string input)
{
return Regex.IsMatch(input, #"\d+");
}
This will handle any occurrence of numbers in the text, regardless of where or how many times they may appear.
use the TextBox.TextChanged event. Then use the same code as you have in the KeyDown event. In fact, you no longer need the keydown event
You can use the JavaScript change event (onchange) instead of the keydown event. It'll check only when the user leaves the textbox though.