C# SQL DataReader:如何只读一次

C# SQL DataReader : How to Read only One time

只有一次,谢谢帮助!

Public string panda(string lola = @"Server=.\SQLEXPRESS; DataBase=panda; Integrated Security=true;")
{
      SqlConnection panda = new SqlConnection(lola);
      panda.Open();
      return lola;         
}

public string Show_details(string Command = "Select name From panda")
{
     SqlConnection cn = new SqlConnection(panda());
     SqlCommand Show;
     SqlDataReader read;

     Show = new SqlCommand(Command, cn);
     cn.Open();

     read = Show.ExecuteReader();

     while (read.Read())
     {
        listBox1.Items.Add(read["name"]);
     }

     return Command;
}

private void button3_Click(object sender, EventArgs e)
{
   Show_details();
}

我正在寻找如何使 reader 读取数据并 post 只在列表框中显示一次!

如果我没有正确理解你的问题,你只想进入 reader 循环一次。 'While',没有双关语的意思,有更有效的方法来解决这个问题,您可以声明一个 bool 标志以查看您是否已经进入循环。一旦进入循环,将其更改为 false,以便在下一次评估 while 条件时,它将评估为 false 结束循环。见下文。

public string Show_details(string Command = "Select name From panda")
{
     SqlConnection cn = new SqlConnection(panda());
     SqlCommand Show;
     SqlDataReader read;

     Show = new SqlCommand(Command, cn);
     cn.Open();

     read = Show.ExecuteReader();

     // Declare flag to see if you've hit the reader yet.
     bool hasntYetRead = true;

     // Add a second condition to determine if to cursor through again
     while (read.Read() && hasntYetRead )
     {
        listBox1.Items.Add(read["name"]);

         // Change the flag to false
         hasntYetRead = false;
     }

     return Command;
}

如果您希望以后能够更改次数或迭代次数,您可以使用计数器。

public string Show_details(string Command = "Select name From panda")
{
     SqlConnection cn = new SqlConnection(panda());
     SqlCommand Show;
     SqlDataReader read;

     Show = new SqlCommand(Command, cn);
     cn.Open();

     read = Show.ExecuteReader();

     // declare counter
     int counter = 0;

     // Add a second condition to determine if to cursor through again
     while (read.Read() && counter < 1) //could get counter to count to user input number
     {
         listBox1.Items.Add(read["name"]);

         // Change the flag to false
         counter++;
     }

     return Command;
}