2014-10-04 42 views
0

所以我有這樣的:C#SQL多個查詢結果劃分爲不同勢文本

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

而且有多個結果,我怎麼能現在不同勢文本框移動他們每個人(我已經創建文本框至今?我只設法獲得相同的結果放進去。

回答

0

這通常是我如何做到這一點....

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(); 

只要確保同時通過他們循環,你的目標是正確的列名,並正確地投。

0

您可以通過每一個數據庫表中的項目需要循環。想想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請給這篇文章讀一讀。

+0

我用你的例子,但爲第二個文本框textBox2.Text = reader [1];我得到錯誤,索引超出了數組的界限。這是否意味着SQL查詢只返回1個結果? – user3062657 2014-10-04 21:48:57

+0

是的,確實如此:-)它在0位置返回了一條記錄。 :-) – 2014-10-05 04:28:21