【问题标题】:why does it freeze?为什么会结冰?
【发布时间】:2016-07-17 12:28:12
【问题描述】:

我的目标是根据组合框的当前值使我的按钮灵活,但问题是当我在特定事件上运行我的程序时,它会冻结,我的语法或我的计算机是否有问题只是慢?

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);
        }          
    }
}

【问题讨论】:

  • while (selected == "ADD") 它怎么会摆脱这种状况???

标签: c# button combobox click selectedindexchanged


【解决方案1】:

您不会更改 while 循环的条件 - 因此,如果它永远为真,那么它总是为真:

string selected = (string)cmbOperation.SelectedItem;

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

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

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

【讨论】:

    【解决方案2】:

    while (selected == "ADD") 是一个永无止境的无限循环。我想你打算这样做:

    if(selected == "ADD")
    

    作为旁注。由于这是一个插入查询,我猜你需要:

    cmDB.ExecuteNoneQuery();
    

    而不是:

    myReader = cmDB.ExecuteReader();
    MessageBox.Show("Client Information has been added to the list");
    while(myReader.Read())
    {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多