首页 > 解决方案 > 转换和查找值

问题描述

我需要帮助找到两个数字(0~274)之间的一个值和一个值,如果该值介于这些值之间,它将允许我的一个表单上的文本为黑色。如果文本为 275~300,则文本将为红色。

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    string Lent = richTextBox1.TextLength.ToString();
    l6.Text = Lent + "/300";
    if (Lent == "275")
    {
        l6.ForeColor = Color.Red;
    }
    else if (Lent == "274")
    {
        l6.ForeColor = Color.Red;
    }
    else if (Lent == "0")
    {
        l6.ForeColor = Color.Red;
    }
}

l6是我的label6,它显示来自 的文本长度richTextBox,例如"0/300". 我试图找到两者之间的值但失败了,我真的需要一些帮助!

标签: c#

解决方案


对范围使用整数比较。

private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        var textLength = richTextBox1.TextLength;
        l6.Text = @"{textLength}/300";

        // Add ranges in condition and set color.
        if (textLength == 0 || textLength <= 274)
        {
            l6.ForeColor = Color.Black; //Whatever color
        }
        else if (textLength > 275)
        {
            l6.ForeColor = Color.Red;
        }
    }

替代且更具可读性的解决方案。

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        var textLength = richTextBox1.TextLength;
        l6.Text = @"{textLength}/300";
        l6.ForeColor = (textLength >= 275) ? Color.Red : Color.Black;
    }

推荐阅读