0

提出这个问题我可能用词错误。这是一个棘手的提议,我迫切需要解决方案:-(

我想以textBox1_KeyDown两种不同的方式触发,但通过基于某些标准按下相同的键。下面的代码将更加清晰。

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (textBox1.Text == "")
        {
            if (e.KeyCode == Keys.Enter)
            {
                textBox1.Text = "x";
            } 
        }


        if (textBox1.Text != "")
        {
            if (e.KeyCode == Keys.Enter)
            {
                 textBox1.Text = "y";
            }
        }
    }

我想要做的是当我按下 textBox1 上的 Enter 按钮时,如果其中没有文本,我希望它显示“x”。如果其中有一些文本,那么我希望文本框在按 Enter 时显示“y”。当我按照上面编码的方式进行操作时,这两个过程都发生在一个实例中。也就是说,当我在textBox1空白处按 Enter 时,它会显示“y”(应该是“x”)。这意味着它首先显示“x”,然后由于文本框中有一个数量,因此文本变为我的代码所调用的“y”。如何分离这两个功能?就像我希望文本框在其空白时仅显示“x”并按 Enter 键,或者当它不为空白时应仅显示“y”并按 Enter 键。

我一定错过了一些愚蠢的东西。谢谢。请给我代码。我几乎不懂技术术语..

4

5 回答 5

3

那是因为两个 if 语句都被执行了。第一个 if 语句执行并使文本框中的文本不为空。这也会导致下一个 if 语句被触发。只需这样做就可以解决它:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (textBox1.Text == "")
    {
        if (e.KeyCode == Keys.Enter)
        {
            textBox1.Text = "x";
        } 
    }


    else if (textBox1.Text != "")
    {
        if (e.KeyCode == Keys.Enter)
        {
             textBox1.Text = "y";
        }
    }
}

注意在第二个 if 语句中添加“else”。

于 2011-03-30T22:30:52.397 回答
1

好吧,首先你可以放入return;嵌套最深的if语句,这样下一个语句if就不会被执行。

您可以做的另一件事是颠倒条件的顺序,因此您if (textBox1.Text != "")在处理程序的顶部而不是底部进行测试。

最后,您可以else在两个条件之间使用。

于 2011-03-30T22:29:46.520 回答
1

根据您在那里写的内容,您可以翻转 if 语句的顺序或将第二个块设置为 else 或 else if。

于 2011-03-30T22:30:03.087 回答
1

你正在寻找这样的东西,所以我相信:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    //determine if text is empty or otherwise equal to 'x'...
    if (textBox1.Text == string.Empty || textBox1.Text != "x")
    {
        //confirmed, set to 'x'...
        textBox1.Text = "x";
    }
    else //and a catch-all for y
    {
        //text wasn't empty or 'x', set to 'y'...
        textBox1.Text = "y";
    }
}

您还可以使用三元运算符以简写方式实现此目的:

//get a copy of the text
var value = textBox1.Text;
//set textbox value to 'x' if not empty or equal to 'x', otherwise 'y'
textBox1.Text = value == string.Empty || value != "x" ? "x" : "y";
于 2011-03-30T22:30:11.973 回答
1

也许我错过了一些东西,但为什么不添加一个 else:

private void textBox1_KeyDown(object sender, KeyEventArgs e)    
{
    if (textBox1.Text == "")         
    {
        if (e.KeyCode == Keys.Enter)
        {
            textBox1.Text = "x";
        }
    }

    else if (textBox1.Text != "")
    {
        if (e.KeyCode == Keys.Enter)
        {
            textBox1.Text = "y";
        }
    }
} 
于 2011-03-30T22:30:18.937 回答