如何在文本框中显示sql数据

本文关键字:显示 sql 数据 文本 | 更新日期: 2023-09-27 18:26:33

我的SQL数据库由一个列id组成,其中包含数字1到30。我想在每次按下按钮时在文本框中显示数字1到30。然而,我的代码只显示第一行,即1。我已经尝试了以下代码:

SqlConnection Conn = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * from id", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
    textBox3.Text = DR1.GetValue(0).ToString();
}
Conn.Close();

如何在文本框中显示sql数据

此行导致问题-

textBox3.Text = DR1.GetValue(0).ToString();

这里CCD_ 1的值被每个循环覆盖。

相反,您应该在每次迭代中附加textBox3值-

textBox3.Text = textBox3.Text + DR1.GetValue(0).ToString();

使用while循环而不是if

您必须循环

While (DR1.read())
{
textBox3.Text += DR1.GetValue(0).ToString();
}