为什么会冻结?

Enr*_*iko 0 c# combobox selectedindexchanged click button

我的目标是让我的按钮灵活,取决于我的组合框的当前值,但问题是当我在该特定事件上运行我的程序它冻结,我的语法有问题或我的电脑只是慢?

private void cmbOperation_SelectedIndexChanged(object sender, EventArgs e)
{
    string selected = (string)cmbOperation.SelectedItem;

    while (selected == "ADD")
    {
        txtID.ReadOnly = true;
        txtLName.ReadOnly = false;
        txtFName.ReadOnly = false;
        txtMI.ReadOnly = false;
        txtGender.ReadOnly = false;
        txtAge.ReadOnly = false;
        txtContact.ReadOnly = false;

        btnOperate.Text = "ADD CLIENT";
    }
}
private void btnOperation_Clicked(object sender, EventArgs e)
{            
    if (cmbOperation.SelectedItem.Equals("ADD"))
    {
        string constring = "datasource=localhost;port3306;username=root";
        string Query = "insert into mybusiness.client_list (LastName,FirstName,MI,Gender,Age,Contact) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + this.txtMI.Text + "','" + this.txtGender.Text + "','" + this.txtAge.Text + "','" + txtContact.Text + "' ;";
        MySqlConnection conDB = new MySqlConnection(constring);
        MySqlCommand cmDB = new MySqlCommand(Query, conDB);
        MySqlDataReader myReader;

        try
        {
            conDB.Open();
            myReader = cmDB.ExecuteReader();
                MessageBox.Show("Client Information has been added to the list");
            while(myReader.Read())
            {
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }          
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

你没有改变while循环的条件- 所以如果它是真的,它将永远是真的:

string selected = (string)cmbOperation.SelectedItem;

while (selected == "ADD")
{
    // Code that doesn't change the value of selected
}
Run Code Online (Sandbox Code Playgroud)

但是,您的代码还有其他重大问题:

  • 您正在UI线程上执行数据库操作.这将挂起UI,直到操作完成.最好使用async/await和异步数据库操作
  • 您的代码容易受到SQL注入攻击,因为您正在从值构建SQL而不是使用参数化SQL.先解决这个问题.
  • 您正在调用ExecuteReader执行插入操作.ExecuteNonQuery改为使用- ExecuteReader专为查询而设计,而您的代码不会查询任何内容.
  • 您应该使用using连接和命令的语句,因此当执行离开using语句的范围时它们会自动关闭- 当前您的连接将一直存在,直到它被完成并进行垃圾收集; 这可能导致挂起.