如何根据文本框中的输入更改标签的前景色和背景色

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

我有一份 windows 表格申请。基于用户年龄(输入),我想根据他们输入的年龄突出显示以下标签之一 "child, preteen, teen, adult"。我目前有一个年龄文本框,可将用户年龄提交到表单下方的标签。

这是我正在使用的: 文本年龄 lblChild (<12) lblPreTeen(13 至 15 岁) lblTeen(16 至 18 岁) lbl成人(18>) btn提交

谢谢。我是编码新手,仍在掌握基础知识。

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

我建议将您的 TextBox 更改为 NumericUpDown (called numAge), if possible. Go to the properties of the NumericUpDown in the Form editor and click the Events button (lightning bolt). If you double-click the 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
        }
    }

如果必须使用 TextBox,请使用 TextChanged 方法。这样你就不需要提交按钮了:

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
        }
    }