【问题标题】:Problem changing condicionally BackColor in a textbox form在文本框表单中条件更改背景颜色的问题
【发布时间】:2020-02-08 18:41:09
【问题描述】:

我正在尝试在 Windows 窗体的文本框中设计一个语句,以便在给定变量的输入为 <>== 时背景颜色会发生变化。

我一直在尝试使用 if/else ifswitch

private void txtPuntosTotalesAGenerar_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (e.KeyChar == (char)Keys.Enter)
        {
            int finalSamplePoints = Convert.ToInt32(Console.ReadLine());
            int try1 = 1500;

            if (finalSamplePoints > try1)
            {
                txtPuntosTotalesAGenerar.BackColor = Color.Orange;
            }
            else if (finalSamplePoints < try1)
            {
                txtPuntosTotalesAGenerar.BackColor = Color.Red;
            }
            else if (finalSamplePoints == try1)
            {
                txtPuntosTotalesAGenerar.BackColor = Color.Green;
            }
        }
    }

使用此代码,我已经能够获得红色背景颜色,但无论我在文本框中引入的值如何,它都不会改变。

【问题讨论】:

  • 考虑在更改颜色后刷新/重绘窗口。您可以尝试在表单上调用 this.Invalidate() 或 this.Refresh()。

标签: c# arcgis arcobjects


【解决方案1】:

问题是 Console.ReadLine() 在按下 Enter 键时总是给你 0 。

我认为你需要像这样修改逻辑

private void txtPuntosTotalesAGenerar_KeyPress(object sender, KeyPressEventArgs e)
{

    if (e.KeyChar == (char)Keys.Enter)
    {
        int finalSamplePoints = Convert.ToInt32(txtPuntosTotalesAGenerar.Text);
        int try1 = 1500;

        if (finalSamplePoints > try1)
        {
            txtPuntosTotalesAGenerar.BackColor = Color.Orange;
        }
        else if (finalSamplePoints < try1)
        {
            txtPuntosTotalesAGenerar.BackColor = Color.Red;
        }
        else if (finalSamplePoints == try1)
        {
            txtPuntosTotalesAGenerar.BackColor = Color.Green;
        }
    }
}

显然您需要添加适当的验证以确保正确处理任何非数字输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多