2010-11-01 46 views
1

我想在文本字段中顯示SqlDataReader(它的唯一行/列數據庫返回)的第一行。我認爲這是正確的語法,但我得到'沒有數據'的錯誤。我可以確保正在使用的sql查詢肯定會返回一個答案,我已經在SQL Server中檢查過它。SqlDataReader [0]爲空

SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection); 
sqlConnection.Open(); 
SqlDataReader reader = sqlCommand.ExecuteReader(); 
Label1.Text = reader[0].ToString(); 

reader[0]似乎沒有顯示任何東西。

回答

4

你需要,如果我沒記錯的話用實際讀取數據:

reader.Read() 

您可以通過迭代或只使用第一個值。

+0

有你去,我的+1。 – Aliostad 2010-11-01 12:09:12

2

您需要撥打read()才能移動到行。它通常用作

while(reader.read()) 
    { 
     // do something 
    } 

在你的情況下把reader.read()分配給標籤之前。

* 還記得總是關閉它 - 所以使用它在using塊。 *

+0

+1擊敗我吧:) – BenW 2010-11-01 12:07:48

0

請閱讀DataReader的文檔。索引器提供基於序號/列號的值。由於您還沒有開始(或正在)通過閱讀器,它將是空的。