简体   繁体   English

如何在C#windowsForm中使用命令单击时暂停和恢复命令

[英]how to pause and resume while command in C# windowsForm with button click

I want to pause my program after it runs the while command once and wait for button4_click to resume for one more iteration. 我想在程序运行一次while命令后暂停程序,然后等待button4_click继续进行一次迭代。 Each click of button4 should run the while loop once. 每次单击button4应该运行一次while循环。

code: 码:

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

If you are wanting to process a single customer record after each click of a button you don't want a while loop. 如果您希望在每次单击按钮后处理一条客户记录,则不希望有while循环。

What you want to do instead is to store your records, close your database connection, and process one record per click of button4. 相反,您要做的是存储记录,关闭数据库连接并在每次单击button4时处理一条记录。

You can't really terminate a while loop the way you are wanting too, it's entirely contrary to their purpose. 您也无法真正按照自己的方式终止while循环,这完全违背了它们的目的。

Try something like this: 尝试这样的事情:

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

Outside of your class (but within the namespace) create the limited-scope class 'YourObject'. 在类之外(但在名称空间中)创建有限范围的类“ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM