[英]how to pause and resume while command in C# windowsForm with button click
我想在程序运行一次while
命令后暂停程序,然后等待button4_click
继续进行一次迭代。 每次单击button4应该运行一次while
循环。
码:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connectString);
conn.Open();
if (this.textBox3.Text != "")
{
this.listView1.Items.Clear();
SqlCommand cmd = new SqlCommand("select * from customer", conn);
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
this.listView1.Items.Add(read.GetValue(0).ToString());
this.listView1.Items.Add(read.GetValue(1).ToString());
this.listView1.Items.Add(read.GetValue(2).ToString());
}
read.Close();
conn.Close();
}
}
如果您希望在每次单击按钮后处理一条客户记录,则不希望有while
循环。
相反,您要做的是存储记录,关闭数据库连接并在每次单击button4时处理一条记录。
您也无法真正按照自己的方式终止while循环,这完全违背了它们的目的。
尝试这样的事情:
private void button2_click()
{
/* Open your database connection, retrieve your results, store them in 'read' as previously */
recordList = new List<YourObject>(); //Define this at the class level, not the method level, so it is accessible to other methods
while(read.Read())
{
recordList.Add(new YourObject(read.GetValue(0).ToString(), read.GetValue(1).ToString(), read.GetValue(2).ToString());
}
/* Close your connections */
}
private void button4_click()
{
//You should probably check to make sure recordList[0] isn't null first
this.listView1.Items.Add(recordList[0].A);
this.listView1.Items.Add(recordList[0].B);
this.listView1.Items.Add(recordList[0].C);
recordList.removeAt[0];
}
在类之外(但在名称空间中)创建有限范围的类“ YourObject”。
private class YourObject
{
string A,B,C;
public YourObject( string a, string b, string c)
{
A = a;
B = b;
C = c;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.