我的目标是根据我的组合框的当前价值使我的按钮变得灵活,但问题是当我在该特定事件上运行我的程序时它会冻结,我的语法是否有问题或者我的计算机是只是慢?
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);
}
}
}
答案 0 :(得分:6)
你没有改变while
循环的条件 - 所以如果它是真的,总是是真的:
string selected = (string)cmbOperation.SelectedItem;
while (selected == "ADD")
{
// Code that doesn't change the value of selected
}
您的代码还有其他重大问题:
ExecuteReader
来执行插入操作。请改用ExecuteNonQuery
- ExecuteReader
专为查询而设计,而您的代码不会查询任何内容。using
语句,因此当执行离开using
语句的范围时它们会自动关闭 - 当前您的连接将一直挂起,直到它完成并收集垃圾;这可能导致挂起。答案 1 :(得分:0)
while (selected == "ADD")
是一个永无止境的无限循环。我想你的意思是:
if(selected == "ADD")
作为旁注。由于这是一个插入查询,我想你需要:
cmDB.ExecuteNoneQuery();
而不是:
myReader = cmDB.ExecuteReader();
MessageBox.Show("Client Information has been added to the list");
while(myReader.Read())
{
}