1

我想在我的程序运行 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();
    }
}
4

1 回答 1

1

如果您希望在每次单击按钮后处理单个客户记录,您不想要while循环。

您想要做的是存储您的记录,关闭您的数据库连接,并在每次单击按钮 4 时处理一条记录。

您也不能真正以您想要的方式终止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;
    }
}
于 2013-04-11T18:53:59.017 回答