【问题标题】:Need help on a Whitelist Key System在白名单密钥系统上需要帮助
【发布时间】:2019-01-07 02:32:44
【问题描述】:

我试图让人们需要获得一个密钥,然后他们必须将密钥输入一个文本框,然后单击一个完成按钮,如果它是正确的,我希望它把他们带到不同的形式。

问题是我希望它位于如果键是其他任何东西而不是正确的键的位置,它会显示一个 mbox,说不正确的键并保持在同一个表单上,但每次我尝试做类似的事情时,它只需要我转到下一个表格,但仍然显示不正确的键。

private void button1_Click_1(object sender, EventArgs e)
{
    if (textBox1.Text == "Aim4last") ;
    Main temp = new Main();
    temp.Region = this.Region;
    temp.Show();
    this.Hide();

    if (textBox1.Text == "") ;
    MessageBox.Show("Incorrect Key");
}

【问题讨论】:

  • 请注意,visual-studio 标签适用于与 Visual Studio 应用程序本身相关的问题,而不是您使用它编写的代码。

标签: c#


【解决方案1】:

您的代码的问题在于您如何定义 if 语句:

if (textBox1.Text == "") ;

末尾的; 表示条件为true 时要执行的代码现在已经完成。我不确定这是否可以编译,但如果可以,则您基本上没有任何操作。

If 语句有两种写法:

if (textBox1.Text == "")
{
    MessageBox.Show("abc");
    // you can place as much code inside the block as you like, and it will only be executed if the condition is true
}

在这种风格中,if 语句将执行其下方的封闭块 ({ ... })。或者,您可以像这样编写if 语句:

if (textBox1.Text == "")
    MessageBox.Show("abc"); // this can be on the same line as the if statement.
    MessageBox.Show("def"); // this line is not part of the if statement and will always execute regardless of the condition being met

在这种风格中,if 语句在满足条件时执行单行代码。注意def MessageBox 不是if 语句的一部分,所以它会一直被执行。

所以,我们应该这样写你的代码:

if (textBox1.Text == "Aim4last")
{
    Main temp = new Main();
    temp.Region = this.Region;
    temp.Show();
    this.Hide();
}
else if (textBox1.Text == "")
{
    MessageBox.Show("Incorrect Key");
}

这导致了一个新问题:我们只有两个条件,"Aim4last"""。文本框可以包含其他值,但不会在键错误时生成消息框。要解决此问题,请将其更改为 else 而不是 else if

if (textBox1.Text == "Aim4last")
{
    Main temp = new Main();
    temp.Region = this.Region;
    temp.Show();
    this.Hide();
}
else
{
    MessageBox.Show("Incorrect Key");
}

【讨论】:

    【解决方案2】:

    请参考https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/if-else

    您没有将逻辑放入代码块中。基本上你的 if 语句什么都不做,代码继续处理每一行。

    if (textBox1.Text == "Aim4last")
    {
        Main temp = new Main();
        temp.Region = this.Region;
        temp.Show();
        this.Hide();
    }
    else if (textBox1.Text == "")
    {
        MessageBox.Show("Incorrect Key");
    }
    

    无法处理的是既不是空白也不是您想要的键。你可能只想做一个 else:

    if (textBox1.Text == "Aim4last")
    {
        Main temp = new Main();
        temp.Region = this.Region;
        temp.Show();
        this.Hide();
    }
    else 
    {
        MessageBox.Show("Incorrect Key");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 2013-04-21
      • 2015-08-27
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多