【问题标题】:C# SQL multiple query results into diffrent textboxC# SQL 多个查询结果到不同的文本框
【发布时间】:2014-10-05 15:42:27
【问题描述】:

所以我有这个:

            Conn.Open();
            SqlCommand Comm3 = new SqlCommand("SELECT answer" + " FROM answers" + " WHERE id_answer=5" , Conn);
            SqlDataReader DR3 = Comm3.ExecuteReader();

并且有多个结果,我现在如何将它们中的每一个移动到不同的文本框中(我已经创建了文本框?直到现在我才设法将相同的结果放入其中。

【问题讨论】:

    标签: c# sql sql-server


    【解决方案1】:

    这通常是我的做法......

       SqlConnection cn = new SqlConnection("my connection string");
        cn.Open();
    
        string sql = "select * from table where column = whatever";
        using (SqlCommand cmd = new SqlCommand(sql,cn))
        {
            SqlDataReader dr = cmd.ExecuteReader();
    
            while (dr.Read())
            {
                myTextBox1.Text = (string)dr["Column1"];
                myTextBox2.Text = (string)dr["Column2"];
                myTextBox3.Text = (string)dr["Column3"];
            }
    
            dr.Close();
        }
    
        cn.Close();
    

    只需确保在循环遍历它们时瞄准正确的列名,并正确投射。

    【讨论】:

      【解决方案2】:

      您需要遍历数据库表中的每个项目。考虑一个foreach 循环,您只需遍历每个项目并以类似方式处理它。

      这是一个示例,

      // Create new SqlDataReader object and read data from the command.
      using (SqlDataReader reader = command.ExecuteReader())
      {
          // while there is another record present
          while (reader.Read())
          {
              // write the data on to the screen
              textBox.Text = reader[0];
          }
      }
      

      这会将读者第一列(答案)的值添加到文本框。现在确保您调用正确的文本框来添加值。

      http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program请阅读这篇文章。

      【讨论】:

      • 我使用了您的示例,但对于第二个文本框 textBox2.Text = reader[1];我收到错误,索引超出了数组的范围。这是否意味着 SQL 查询只返回了 1 个结果?
      • 是的,确实 :-) 它在 0 位置返回了一条记录。 :-)
      猜你喜欢
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多