如何从动态TextBox中的Ms数据库获取所有数据[行]

时间:2015-05-15 02:28:43

标签: c# database ms-access

我有这样的代码

int cLeft=0;
public System.Windows.Forms.TextBox AddNewTextBox()
{
    System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
    string query = " select * FROM DotMatrix;
    command.CommandText = query;
    OleDbDataReader reader = command.ExecuteReader();
    this.Controls.Add(txt);
    txt.Top = (cLeft*25) + 124;
    txt.Left = 50;
    txt.Height = 20;
    txt.Width = 259;
    while (reader.Read())
    {
        txt.Text=reader["Pertanyaan"].ToString();
    }
    if (txt.Text=="")
    {
        MessageBox.Show("Pertanyaan  Habis , Akan Redirect Ke Hasil");
    }
    cLeft = cLeft + 1;
    return txt;
}

private void textBox1_TextChanged_1(object sender, EventArgs e)
{
   AddNewTextBox();
}

我的问题是,为什么textBox只显示数据库中的1行??? 我想在Pertanyaan Row显示数据[Row] 谢谢你的回答

1 个答案:

答案 0 :(得分:0)

此行循环遍历每一行并不断覆盖文本框值:

while (reader.Read())
{
    txt.Text=reader["Pertanyaan"].ToString();
}

因此,一遍又一遍地分配相同的文本框。

您希望将文本框创建代码移动到循环内部,如下所示:

while (reader.Read())
{
    System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
    txt.Top = (cLeft*25) + 124;
    txt.Left = 50;
    txt.Height = 20;
    txt.Width = 259;
    txt.Text=reader["Pertanyaan"].ToString();
    if (txt.Text=="")
    {
        MessageBox.Show("Pertanyaan  Habis , Akan Redirect Ke Hasil");
    }
    this.Controls.Add(txt);
}