C#控件事件sender用法

一般遇到sender的地方在控件事件中,我们以TextBox内容改变事件为例:

private void txt_Xdelta_TextChanged(object sender, EventArgs e)

sender作用:sender用来获取当前触发事件的控件。

了解完这个功能后,我们用代码尝试一下改变控件的属性。

    private void txt_Xdelta_TextChanged(object sender, EventArgs e)
    {
        ChangeColorIfNumbersFloat(sender as TextBox);
    }

    public static void ChangeColorIfNumbersFloat(TextBox tx)
    {
        float t = 0;
        if (float.TryParse(tx.Text, out t))
        {
            //Show green if only numbers
            tx.BackColor = Color.PaleGreen;
        }
        else if (tx.Text == "")
        {
            //Show defaul color if nothing
            tx.BackColor = SystemColors.Window;
        }
        else
        {
            //Show red if not only numbers
            tx.BackColor = Color.SandyBrown;
        }
    }

嗯,看上起,感觉棒棒的!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容