2013-04-11 101 views
1

我想在程序運行while命令後暫停程序,並等待button4_click恢復一次迭代。每按一下按鈕4應該運行一次while循環。如何在C#windowsForm中使用按鈕單擊時暫停和恢復命令

代碼:

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

我編輯了你的問題來闡明你的意思並修復一些小的語法問題。如果您認爲我沒有改善您的問題,請隨時恢復。 – Jeff 2013-04-11 18:53:14

+0

更好地使用conn,cmd和read。如果拋出異常(例如,查詢超時),您的關閉調用將被跳過。 – 2013-04-11 18:56:07

回答

1

如果你想處理一個客戶記錄按鈕的每次點擊後,你不想while循環。

你想要做的就是存儲你的記錄,關閉你的數據庫連接,並且每按一次按鈕處理一條記錄。

你真的不能終止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; 
    } 
}