EDIT: This question has been solved using "sender" (see answer below)--thank you to everyone who left comments!
I'm trying to create a method that I can call within any number of text fields that will automatically check if the first char in the field is a period, and, if there isn't, to add a period (e.g. "exe" -> ".exe") whenever the user clicks away.
The actual text-check-and-change I got working, but I'm trying to figure out how to have the method automatically change whichever textBox called it. (That way, I'm not copying and pasting code and specifying the textBox name every time.)
The "this" is basically a placeholder at this point until I figure it out:
// making sure the first char in the text box always has a . for the extension
public void periodFix()
{
this.Text = this.Text.Trim();
if (this.Text.Length > 0)
{
char[] textBoxContents = this.Text.ToCharArray();
if (textBoxContents[0] != '.')
{
string tempString = "." + this.Text;
this.Text = tempString;
}
}
else
{
this.Text = ".";
}
}
private void textBox7_Leave_1(object sender, EventArgs e)
{
periodFix();
}
I feel like there has to be a way to do this, but I'm still learning C# and my vocab to identify specifically what it is I'm trying to do is lacking.
In the code above, I tried using "this", which hasn't worked.
I tried using "sender" in the place of "this" which didn't work.
I also tried passing in by reference (ref this, ref textBox, etc.) and none of the syntax seemed to be working right.
Thanks to Ňɏssa and hallibut in the comments. I thought there was a fundamental problem with using sender, but the issue was that Windows needed the full path for the TextBox's object type and I was overthinking the problem.
Here's the corrected code that worked:
private void periodFix(object sender)
{
// making sure the first char in the text box always has a . for the extension
System.Windows.Forms.TextBox tb = System.Windows.Forms.TextBox)sender;
tb.Text = tb.Text.Trim();
if (tb.Text.Length > 0)
{
char[] textBoxContents = tb.Text.ToCharArray();
if (textBoxContents[0] != '.')
{
string tempString = "." + tb.Text;
tb.Text = tempString;
}
}
else
{
tb.Text = ".";
}
}
private void textBox7_Leave_1(object sender, EventArgs e)
{
// making sure the first char in the text box always has a . for the extension
periodFix(sender);
}