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

时间:2017-02-17 21:08:01

标签: c# textbox label back

我有一个Windows窗体应用程序。根据用户年龄(输入),我想根据他们为年龄输入的内容突出显示以下标签之一“儿童,青春期,青少年,成人”。我目前有一个年龄的文本框,可以将用户年龄提交到表单下方的标签。

这是我正在使用的: txtAge lblChild(< 12) lblPreTeen(13到15) lllTeen(16到18) lblAdult(18&GT) btnSubmit按钮

感谢。我是编码新手并且仍然掌握基础知识。

2 个答案:

答案 0 :(得分:2)

如果可能,我建议将TextBox更改为NumericUpDown(名为numAge)。转到表单编辑器中NumericUpDown的属性,然后单击“事件”按钮(闪电)。如果双击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
        }
    }

答案 1 :(得分:0)

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