Amirhossein Hosseini
Amirhossein Hosseini

Reputation: 15

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. Each click of button4 should run the while loop once.

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

Upvotes: 1

Views: 452

Answers (1)

Jeff
Jeff

Reputation: 2861

If you are wanting to process a single customer record after each click of a button you don't want a while loop.

What you want to do instead is to store your records, close your database connection, and process one record per click of button4.

You can't really terminate a while loop the way you are wanting too, it's entirely contrary to their purpose.

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'.

private class YourObject
{
    string A,B,C;

    public YourObject( string a, string b, string c)
    {
        A = a;
        B = b;
        C = c;
    }
}

Upvotes: 1

Related Questions