如何从方法本身修改调用该方法的对象(textBox)?

问题描述 投票:0回答:1

我正在尝试创建一个可以在任意数量的文本字段中调用的方法,该方法将自动检查字段中的第一个字符是否是句点,如果不是,则添加句点(例如“exe " -> ".exe") 每当用户点击离开时。

我正在工作的实际文本检查和更改,但我试图弄清楚如何让该方法自动更改whichevertextBox 调用它。 (这样,我就不会每次都复制和粘贴代码并指定文本框名称。)

“这个”基本上是一个占位符,直到我弄清楚为止:

        // 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();
        }

我觉得必须有一种方法可以做到这一点,但我仍在学习 C#,而且我缺乏词汇来明确我正在尝试做什么。

在上面的代码中,我尝试使用“this”,但没有成功。

我尝试使用“sender”代替“this”,但这不起作用。

我还尝试通过引用传递(ref this、ref textBox 等),但所有语法似乎都无法正常工作。

c# object methods reference sender
1个回答
0
投票

感谢评论中的Ňɏssa和大比目鱼。我认为使用发件人存在一个根本问题,但问题是 Windows 需要 TextBox 的完整路径,而我对这个问题想得太多了。

这是有效的更正代码:

        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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.