简体   繁体   English

如何根据输入到文本框的方式更改标签的原色和底色

[英]How to change the forecolor and backcolor of a label based on input into a textbox

I have a windows form application. 我有一个Windows窗体应用程序。 Based on a users age(inputting), I want to highlight one of the following labels "child, preteen, teen, adult" based on what they enter for age. 根据用户的年龄(输入),我想根据他们输入的年龄来突出显示以下标签之一:“儿童,青春期,青少年,成人”。 I currently have a textbox for age that submits the users age to a label further down the form. 我目前有一个年龄文本框,用于将用户年龄提交到表单下方的标签。

Here is what I am using: txtAge lblChild (<12) lblPreTeen(13 to 15) lblTeen(16 to 18) lblAdult(18>) btnSubmit 这是我正在使用的:txtAge lblChild(<12)lblPreTeen(13至15)lblTeen(16至18)lblAdult(18>)btnSubmit

Thanks. 谢谢。 I am new to coding and still grasping the basics. 我是编码新手,仍然掌握基本知识。

I'd recommend changing your TextBox to a NumericUpDown (called numAge), if possible. 如果可能,我建议您将TextBox更改为NumericUpDown (称为numAge)。 Go to the properties of the NumericUpDown in the Form editor and click the Events button (lightning bolt). 在表单编辑器中转到NumericUpDown的属性,然后单击“事件”按钮(闪电)。 If you double-click the ValueChanged option, it will create the stub for the following method: 如果双击ValueChanged选项,它将为以下方法创建存根:

private void numAge_ValueChanged(object sender, EventArgs e)
    {
        if (numAge.Value > 0 && numAge.Value < 13)
        {
            // Child
            // Highlight label
        }
        else if (numAge.Value > 12 && numAge.Value < 16)
        {
            // Pre-Teen
            // Highlight label
        }
        else if (numAge.Value > 15 && numAge.Value < 19)
        {
            // Teen
            // Highlight label
        }
        else if (numAge.Value > 18)
        {
            // Adult
            // Highlight label
        }
        else
        {
            // Clear the highlights
        }
    }

If you must use a TextBox, use the TextChanged method. 如果必须使用TextBox,请使用TextChanged方法。 That way you don't need the Submit Button: 这样,您就不需要“提交”按钮:

private void txtAge_TextChanged(object sender, EventArgs e)
    {
        int txtAgeValue = 0;
        if (!string.IsNullOrWhiteSpace(txtAge.Text))
        {
            txtAgeValue = int.Parse(txtAge.Text);
        }
        if (txtAgeValue > 0 && txtAgeValue < 13)
        {
            // Child
            // Highlight label
        }
        else if (txtAgeValue > 12 && txtAgeValue < 16)
        {
            // Pre-Teen
            // Highlight label
        }
        else if (txtAgeValue > 15 && txtAgeValue < 19)
        {
            // Teen
            // Highlight label
        }
        else if (numAge.Value > 18)
        {
            // Adult
            // Highlight label
        }
        else
        {
            // Clear the highlights
        }
    }

在文本框中输入事件,您可以使用一些if语句更新相关的标签颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM