Reputation: 514
First of all, I know that there are probably better solutions and I am very willing to listen to those solutions. I have searched around the internet looking for a problem like this but am unable to find one that works so far. I have multiple textboxes on a form, when the user clicks on the textbox I run a method that finds out which textbox is focused, gets the tag of that textbox and the name of the textbox both as strings (TextboxX and test). My goal is to mask the textboxes with for example 'Email' and when the user clicks on the textbox the textbox forecolor changes to black and the textbox text is null, with as little code as possible. Here is the code i have for that.
public void masked()
{
if (textboxX.Text == test)
{
textboxX.ForeColor = Color.Black;
textboxX.Text = "";
}
else
{
textboxX.Select(0, textboxX.Text.Length);
}
}
When the textbox is clicked this is what it does currently.
private void txtSignup_email_Click(object sender, EventArgs e)
{
textboxX = txtSignup_email;
test = "Email";
masked();
}
The reason for this is that I have 7 textboxes, it will save me about 14 lines of code that is actually not necessary. Thanks in advance.
Upvotes: 0
Views: 408
Reputation: 3929
OK there are a few things that can be done better.
First of all you can use Password instead of TextBox which is automatically masked and can't be seen if I understand you requirement correctly.
Second thing is what ainwood said in the comment you can point all clicked or focused events of your textboxes to a single method. Event handler methods have two parameters sender
and e
. The former is of type object
and shows who called this method in your case you can cast is as a TextBox and that will be calling textbox. The cast operation is like this:
var textBox = sender as TextBox;
if (textBox != null)
{
//Do what you want with textBox here
}
Also if you use the new C# 7 you can do (Which is not any different internally just better to read):
if (sender is TextBox textBox)
{
//Do what you want with textBox here
}
Upvotes: 2