Passing a textbox to a void - c#

I'm not sure if I'm using the wrong terminology so that may be why my searching has not turned up anything.
I have a bunch of text boxes that I want to validate and check that they don’t contain apostrophes. The code that I have is:
public void apostropheCheck(TextBox fieldName)
{
Match m = Regex.Match(fieldName.Text, #"'");
if (m.Success)
{
validationErrorProvider.SetError(fieldName, "Field can not contain apostrophes");
}
else if (!m.Success)
{
validationErrorProvider.SetError(fieldName, "");
}
}
and the validation on the textbox is:
private void FirstNameTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
//Checks for apostrophes
apostropheCheck(FirstNameTextBox);
}
However when I run this the value that gets passed to the void is the text that is in the text box (e.g ‘John’ or ‘Mary’) I could get this to work just using the code that’s in the void for each validation event but that would be repeating myself a lot. Is there a better way?

You can have one common handler and use that for all of the textboxes' Validating event.
private void CommonTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
//Checks for apostrophes
apostropheCheck((TextBox)sender);
}

The sender object of the event is a TextBox, so you can cast it to a text box and repeat the same event handler for all of the text boxes in your application
private void FirstNameTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
apostropheCheck(((TextBox)sender).Text);
}

Terminology: you are referring to your function apostropheCheck as the void which is its return type the standard way is to use the function name apostropheCheck.
All of you text boxes can be validated using the same function if you replace the name of the text box in the code with sender ex.
private void FirstNameTextBox_Validating(object sender,System.ComponentModel.CancelEventArgs e)
{
//Checks for apostrophes
apostropheCheck((TextBox)sender);
}

Related

TextBox.Text without the suffix of the appended part of Autocomplete

Is there a way to get the Text in a TextBox that has an Autocomplete that appends text, but without the part that is appended? I want to use this text in the Textbox_TextChanged-event. This code doesn't work
private void Textbox_TextChanged(object sender, EventArgs e)
{
var t = textbox.Text.Substring(0, textbox.SelectionStart);
}
It seems the TextChanged-event fires when the autocomplete-text is appended, but the selection of the appended text is applied after that.
E.g. if the user types in ho and the autocomplete has an entry house, the textbox contains the text house, but the use is selected and can be overwritten when the user continues typing. I want to get the ho-part, because that is the text the user has typed in, without the use-part, which doesn't come from the user.
Question is some what confusing, I have provide an answer as I understood it.
Text change event fires when you change text in the textbox. You can use suggest instead of appending it
Assume that textbox name is "Textbox1"
private void Textbox1_TextChanged(object sender, EventArgs e)
{
this.Textbox1.AutoCompleteMode =
System.Windows.Forms.AutoCompleteMode.Suggest;
var t = Textbox1.Text;
}
I solved it with a delay, so the textbox has time to apply the selection. This seems to work so far, but could be an issue if the applying of the selection takes longer than the wait-time.
private async void Textbox_TextChanged(object sender, EventArgs e)
{
await Task.Delay(200);
var t = textbox.Text.Substring(0, textbox.SelectionStart);
}

Using a generic clear textbox method on event

I've got a program with a lot of text boxes that I've got text in that I want to be cleared on _click and then reset to default if nothing is entered and the user clicks away.
The way I was going to do it is clearly inefficient, having to name the text box each time and I'd like to know how I could go about streamlining it.
this is what I've got at the minute, and I'd have to change the txtUserName for the text box field name each time
private void txtUserName_Click(object sender, EventArgs e)
{
txtUserName.Text = ""
txtUserName.ForeColor = Color.Black;
}
is there a way I can do essentially
private void txtAnyTextBox_Click(object sender, EventArgs e)
{
string caller = //Get this textbox name
this.ClearBoxes(caller)
}
void ClearBoxes(string Caller)
{
Caller.txt.Text = "";
//..... and so on
}
Yes, you can try this (though it's not generic but there is no need for generics in this case):
private void txtAnyTextBox_Click(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
if(tb != null) tb.Text = "";
}
And you can attach this method to all your textBoxes Click event.
textBox1.Click += txtAnyTextBox_Click;
textBox2.Click += txtAnyTextBox_Click;
I don't think this is gonna work:
void ClearBoxes(string Caller)
{
Caller.txt.Text = "";
//..... and so on
}
If you want to use ClearBoxes method you should pass it your TextBox element.But there is no need for this,you can directly clear your textBox as shown above code.
Also if you want to clear all TextBoxes in the same time,for example one button click you can use this:
private void button1_Click(object sender, EventArgs e)
{
foreach (var tBox in this.Controls.OfType<TextBox>())
{
tBox.Text = "";
}
}
You can use the sender argument for that.
private void txtAnyTextBox_Click(object sender, EventArgs e)
{
var textbox = sender as TextBox;
this.ClearTextbox(textbox)
}
private void ClearTextbox(TextBox textbox)
{
textbox.Text = "";
//...
}
You can get name of textbox from sender of event:
private void txtAnyTextBox_Click(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
string caller = textBox.Name;
this.ClearBoxes(caller); // call your custom method
}
If you want to simply clear textbox text, then you don't need to get its name - you can use it's Clear() method:
private void txtAnyTextBox_Click(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.Clear();
}
Also you can consider creation of custom textbox, which will have some default value and will resent itself to default when clicked:
public class CustomTextBox : TextBox
{
public string DefaultText { get; set; }
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
Text = DefaultText;
}
}
Use custom textboxes instead of default textboxes, and provide DefaultText value for each custom textbox which should reset itself to something more meaningful than empty string (you can use Properties window for that).
This would be quite nasty - as you'd cause a page reload every time someone clicked in the text box.
A far simpler way would be to do it in javascript.
just add a function to clear the text box, and then maybe use a css selector to enable the function for every text box you want to use it in.
e.g.
<input type="text" class="clearme" />
$(".clearme").click(function() {
$(this).val('');
});
this will do it all client side without causing any post backs.

Validate input empty textbox c#

I am trying to validate textboxes for empty values. If the textbox is empty and loses focus, an error has to show and the textbox has to receive focus again.
Reading about this I came across the Validating event, which can be cancelled through e.Cancel. However when I try to do this, I get an error message.
My code:
private void CheckInput(CancelEventArgs e, TextBox tb)
{
ErrorProvider error = new ErrorProvider();
if (!string.IsNullOrEmpty(tb.Text))
{
error.SetError(tb, "*");
e.Cancel = true;
}
else
{
error.SetError(tb, "");
}
}
private void tbTitel_Validated(object sender, CancelEventArgs e)
{
CheckInput(e, tbTitel);
}
And the error I get is the following:
Error 1 No overload for 'tbTitel_Validated' matches delegate 'System.EventHandler'
How can I fix this?
The validating uses this delegate:
private void tbTitel_Validating(object sender, CancelEventArgs e)
{
}
The validated event uses this:
private void tbTitel_Validated(object sender, EventArgs e)
{
}
You want to use the Validating event (you should link you eventhandler to the validating event, not the validated event. This way you can cancel it.
You probably clicked the validating first and copy/paste/selected the eventhandler name into the validated event. (designer)
The error occurs, because tbTitel_Validated doesnt have CancelEventArgs in its signature.
Take a look at this thread for further information:
No overload for 'method' matches delegate 'System.EventHandler'
Conclusion: Use tbTitel_Validating instead.
You should use the Validating event to execute your checks, not the Validated event.
The two events have different signatures. The Validated event receives the simple EventArgs argument, while the Validating event receives the CancelEventArgs argument that could be used to revert the focus switch.
Said that, it seems that your logic is wrong.
// error if string is null or empty
// if (!string.IsNullOrEmpty(tb.Text))
if (string.IsNullOrEmpty(tb.Text))
{
error.SetError(tb, "*");
e.Cancel = true;
}
else
{
error.SetError(tb, "");
}
Alwasy use validation statements at Object.Validated event handler
Likewise:
private void textBox1_Validated(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) || textBox1.Text == "")
{
MessageBox.Show("Please use valid data input!!");
}
}

How to get the NEW text in TextChanged?

In a TextBox I'm monitoring the text changes. I need to check the text before doing some stuff. But I can only check the old text in the moment. How can I get the new Text ?
private void textChanged(object sender, EventArgs e)
{
// need to check the new text
}
I know .NET Framework 4.5 has the new TextChangedEventArgs class but I have to use .NET Framework 2.0.
Getting the NEW value
You can just use the Text property of the TextBox. If this event is used for multiple text boxes then you will want to use the sender parameter to get the correct TextBox control, like so...
private void textChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if(textBox != null)
{
string theText = textBox.Text;
}
}
Getting the OLD value
For those looking to get the old value, you will need to keep track of that yourself. I would suggest a simple variable that starts out as empty, and changes at the end of each event:
string oldValue = "";
private void textChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if(textBox != null)
{
string theText = textBox.Text;
// Do something with OLD value here.
// Finally, update the old value ready for next time.
oldValue = theText;
}
}
You could create your own TextBox control that inherits from the built-in one, and adds this additional functionality, if you plan to use this a lot.
Have a look at the textbox events such as KeyUp, KeyPress etc. For example:
private void textbox_KeyUp(object sender, KeyEventArgs e)
{
// Do whatever you need.
}
Maybe these can help you achieve what you're looking for.
Even with the older .net fw 2.0 you should still have the new and old value in the eventArgs if not in the textbox.text property itself since the event is fired after and not during the text changing.
If you want to do stuff while the text is being changed then try the KeyUp event rather then the Changed.
private void stIDTextBox_TextChanged(object sender, EventArgs e)
{
if (stIDTextBox.TextLength == 6)
{
studentId = stIDTextBox.Text; // Here studentId is a variable.
// this process is used to read textbox value automatically.
// In this case I can read textbox until the char or digit equal to 6.
}
}

c# winforms events restore textbox contents on escape

Using c# in 2008 Express. I have a textbox containing a path. I append a "\" at the end on Leave Event. If the user presses 'Escape' key I want the old contents to be restored. When I type over all the text and press 'Escape' I hear a thump and the old text isn't restored. Here what I have so far ...
public string _path;
public string _oldPath;
this.txtPath.KeyPress += new System.Windows.Forms.KeyPressEventHandler(txtPath_CheckKeys);
this.txtPath.Enter +=new EventHandler(txtPath_Enter);
this.txtPath.LostFocus += new EventHandler(txtPath_LostFocus);
public void txtPath_CheckKeys(object sender, KeyPressEventArgs kpe)
{ if (kpe.KeyChar == (char)27)
{
_path = _oldPath;
}
}
public void txtPath_Enter(object sender, EventArgs e)
{
//AppendSlash(sender, e);
_oldPath = _path;
}
void txtPath_LostFocus(object sender, EventArgs e)
{
//throw new NotImplementedException();
AppendSlash(sender, e);
}
public void AppendSlash(object sender, EventArgs e)
{
//add a slash to the end of the txtPath string on ANY change except a restore
this.txtPath.Text += #"\";
}
Thanks in advance,
Your txtPath_CheckKeys function assigns the path to the old path, but never actually updates the Text in the TextBox. I suggest changing it to this:
public void txtPath_CheckKeys(object sender, KeyPressEventArgs kpe)
{
if (kpe.KeyCode == Keys.Escape)
{
_path = _oldPath;
this.txtPath.Text = _path;
}
}
The Control.Validating event might help you.
It describes the order in which events are triggered. So, choosing the event that best suits your need will make it easier to implement this feature.
It might be too much for the need, but trying to Invalidate the control might help too.
Let me know whether it helps.

Categories

Resources