C# 中的多个条件和 MySQLConnections 问题

Multiple conditions and MySQLConnections issue in C#

我有一个按钮单击事件,用于检查表单上多个输入元素内的条件。文本框、单选按钮、组合按钮等

此外,该方法检查用户名的文本条目是否唯一或是否已存在于数据库中。如果用户满足所有条件,则激活 else 语句并将条目存储在数据库中。

这是下面的方法:

    private void button2_Click_2(object sender, EventArgs e)
    {

        int Vid_Smetka;

        if (radioNewAdmin.Checked)
        {
            Vid_Smetka = 1;
        }
        else
        {
            Vid_Smetka = 0;
        }


        if (txtNewUser.Text == String.Empty)
        {
            MessageBox.Show("Корисничкото име е празно. Ве молиме пополнете го полето.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (txtNewFullname.Text == String.Empty)
        {
            MessageBox.Show("Ве молиме пополнете го полето за целосно име и презиме.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (txtNewEmail.Text == String.Empty || !txtNewEmail.Text.Contains('@'))
        {
            MessageBox.Show("Ве молиме пополнете го полето за email. Користете валидна e-mail адреса.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (txtNewPassword.Text.Length < 6)
        {
            MessageBox.Show("Ве молиме внесете најмалку 6 карактери во лозинката.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        else if (!txtNewPassword.Text.Any(x => char.IsUpper(x)))
        {
            MessageBox.Show("Ве молиме внесете барем една голема буква во лозинката.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (!txtNewPassword.Text.Any(x => char.IsLower(x)))
        {
            MessageBox.Show("Ве молиме внесете барем една мала буква во лозинката.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (txtNewPassword.Text != txtNewRepeatPassword.Text)
        {
            MessageBox.Show("Лозинките не се совпаѓаат. Ве молиме обидете се повторно.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        else if (!radioNewAdmin.Checked && !radioNewUser.Checked)
        {
            MessageBox.Show("Ве молиме селектирајте тип на сметка.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        else if (string.IsNullOrEmpty(comboNewFunction.Text))
        {
            MessageBox.Show("Ве молиме функција на корисникот на сметката во училиштето.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        else if (txtNewUser.Text != String.Empty)
        {

            MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["#.Properties.Settings.ConnectionString"].ConnectionString);

            conn.Open(); //Try to open the connection to the MySql database

            //Check if there is a row with credentials entered in the form
            MySqlDataAdapter sda = new MySqlDataAdapter("SELECT Count(*) FROM #.# WHERE Korisnik = '" + txtNewUser.Text + "'", conn);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            //Initiate a new connection string

            if (dt.Rows[0][0].ToString() != "0")
            {
                MessageBox.Show("Корисничкото име е зафатено. Ве молиме обидете внесете уникатно.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            conn.Close();
        }
        else
        {

            var sqlCommand = "INSERT INTO #.#" +
            "(Korisnik, Lozinka, Vid_Smetka, email, user_function, full_name) " +
            "VALUES ('" + this.txtNewUser.Text + "', '" + this.txtNewPassword.Text + "', '" + Vid_Smetka + "', " +
            "'" + this.txtNewEmail.Text + "', '" + this.comboNewFunction.Text + "', '" + this.txtNewFullname.Text + "');";

            //Initiate a new connection string

            try
            {
                using (MySqlConnection con = new MySqlConnection(conString))
                {
                    MySqlCommand cmdDatabase = new MySqlCommand(sqlCommand, con);
                    con.Open();
                    MySqlDataReader myReader;
                    myReader = cmdDatabase.ExecuteReader();
                    dataGridView1.DataSource = loadData().Tables[0];

                    MessageBox.Show("Зачувано.", "Известување", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    panelNew.Visible = false;

                }
            }
            catch (Exception ex)

            {
                MessageBox.Show(ex.Message);
            }


        } 
    }

这显然很简单。但是,出于某种原因,当满足所有其他条件时,else 语句不会执行。

我在使用 MySQLConnection 时出错了?有什么提示我可能弄错了吗?

如果这一段运行s:

else if (txtNewUser.Text != String.Empty)
    {

        MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["#.Properties.Settings.ConnectionString"].ConnectionString);

        conn.Open(); //Try to open the connection to the MySql database

        //Check if there is a row with credentials entered in the form
        MySqlDataAdapter sda = new MySqlDataAdapter("SELECT Count(*) FROM #.# WHERE Korisnik = '" + txtNewUser.Text + "'", conn);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        //Initiate a new connection string

        if (dt.Rows[0][0].ToString() != "0")
        {
            MessageBox.Show("Корисничкото име е зафатено. Ве молиме обидете внесете уникатно.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        conn.Close();
    }

...然后它将退出整个 if 语句,所以这个...

else
    {

        var sqlCommand = "INSERT INTO #.#" +
        "(Korisnik, Lozinka, Vid_Smetka, email, user_function, full_name) " +
        "VALUES ('" + this.txtNewUser.Text + "', '" + this.txtNewPassword.Text + "', '" + Vid_Smetka + "', " +
        "'" + this.txtNewEmail.Text + "', '" + this.comboNewFunction.Text + "', '" + this.txtNewFullname.Text + "');";

        //Initiate a new connection string

        try
        {
            ...
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

...之后不会运行。如果您希望在检查用户名是唯一的后 运行 INSERT INTO 代码,请将代码的最后一部分更改为:

else if (txtNewUser.Text != String.Empty)
    {

        MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["#.Properties.Settings.ConnectionString"].ConnectionString);

        conn.Open(); //Try to open the connection to the MySql database

        //Check if there is a row with credentials entered in the form
        MySqlDataAdapter sda = new MySqlDataAdapter("SELECT Count(*) FROM #.# WHERE Korisnik = '" + txtNewUser.Text + "'", conn);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        //Initiate a new connection string

        if (dt.Rows[0][0].ToString() != "0")
        {
            MessageBox.Show("Корисничкото име е зафатено. Ве молиме обидете внесете уникатно.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            con.Close();

            var sqlCommand = "INSERT INTO #.#" +
                "(Korisnik, Lozinka, Vid_Smetka, email, user_function, full_name) " +
                "VALUES ('" + this.txtNewUser.Text + "', '" + this.txtNewPassword.Text + "', '" + Vid_Smetka + "', " +
                "'" + this.txtNewEmail.Text + "', '" + this.comboNewFunction.Text + "', '" + this.txtNewFullname.Text + "');";

            //Initiate a new connection string

            try
            {
                using (MySqlConnection con = new MySqlConnection(conString))
                {
                    MySqlCommand cmdDatabase = new MySqlCommand(sqlCommand, con);
                    con.Open();
                    MySqlDataReader myReader;
                    myReader = cmdDatabase.ExecuteReader();
                    dataGridView1.DataSource = loadData().Tables[0];

                    MessageBox.Show("Зачувано.", "Известување", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    panelNew.Visible = false;

                    con.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }