2013-05-06 49 views
2

我正在使用Visual Studio 2010,並且添加了一個新項目作爲report.mdf作爲我的項目數據庫;我創建了一個表Table1,並且我手動添加了一條記錄到Table1;但是當我試圖選擇數據,我不能做到這一點,得到這個錯誤:我的選擇命令不起作用

invalid attempt to read when no data is present

這是我的代碼:

SqlCommand objcomand = new SqlCommand(); 

SqlConnection con = new SqlConnection(); 
[email protected]"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\EHSAN\My Documents\Visual Studio 2010\Projects\report\report\App_Data\report.mdf;Integrated Security=True;User Instance=True"; 

objcomand.Connection = con; 
objcomand.CommandText = "select * from Table1"; 

con.Open(); 

SqlDataReader reader1 = objcomand.ExecuteReader(); 
string i = reader1.GetValue(1).ToString(); 

con.Close(); 

回答

2

你必須在DataReader推進到數據的下一個塊SqlDataReader.Read

string i = null; 
// use using for everything that implements IDisposable like a Connection or a DataReader 
using(var reader1 = objcomand.ExecuteReader()) 
{ 
    // a loop since your query can return multiple records 
    while(reader1.Read()) 
    { 
     // if the field actually is the first you have to use GetString(0) 
     i = reader1.GetString(1); 
    } 
} 
+0

好吧,我說,我手動添加一個字段,以我的表,所以reader.read()應該是真實的,所以我沒有使用權it.am我!? – 2013-05-06 20:22:32

+1

@sarahsh - 正確的,它不僅返回true;它還將'SqlDataReader'推進到結果中的第一條記錄。 – 2013-05-06 20:24:33

+0

是的,真的,我不知道它是重要的,對我來說太令人興奮了,非常感謝你。 – 2013-05-06 20:31:03