2012-10-07 35 views
1

我需要一些幫助來理解我的錯誤。我想從表中讀取數據,但是我得到錯誤,例如「行/列沒有數據」。我不明白,因爲我實際上有行和列在那裏。的WinForms。謝謝!DataReader錯誤 - 「行/列沒有數據」 - 數據存在時?

//this is how i insert data into table, works fine 
    public void b1_Click(object sender, EventArgs e) 
    { 
     SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name, LastName) VALUES (@Name, @LastName)", conn); 
     command.Parameters.AddWithValue("@Name", l1.Text); 
     command.ExecuteNonQuery(); 
    } 

    //this is how i try to read data from the same table 
    public void b2_Click(object sender, EventArgs e) 
    { 
     SqlCeConnection conn = new SqlCeConnection(@"Data Source=C:test.sdf"); 
     conn.Open(); 
     SqlCeCommand command = new SqlCeCommand("SELECT * FROM tbl1", conn); 
     SqlCeDataReader reader = command.ExecuteReader(); 

     //error here 
     string Name = reader.GetString(0); 
     label.Text = Name; 
    } 
+0

請務必包括*僅*的相關代碼下一次(繼續前進,現在去掉無關的代碼);方法定義也可以被刪除,因爲它不適用於問題。 – 2012-10-07 23:21:22

回答

1

問題與結果加載。

SqlCeDataReader reader = command.ExecuteReader(); 

while (reader.Read()) 
{ 
    string Name = reader.GetString(0); 
} 

因此,您使用Read方法遍歷結果。或者,如果你只是有一個結果,那麼你也可以使用ExecuteScalar

string Name = reader.ExecuteScalar().ToString(); 
+0

非常感謝! –

+0

關鍵在於在結果可以從讀取器讀取之前,必須調用一次Read()* *它首先在第一個結果之前定位*;例如'reader.Read(); string Name = reader.GetString(0);'本來就足夠了(假設至少有一行被返回)。 – 2012-10-07 23:19:18

1

在這個序列中

SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name, LastName) VALUES (@Name, @LastName)", conn); 
    command.Parameters.AddWithValue("@Name", l1.Text); 
    command.ExecuteNonQuery(); 

你不設置第二個參數@LastName所以它應該已經失敗。如果您之前沒有在表格中存儲過記錄,則無法從中選擇。

這一點,事實上,你是不是叫reader.Read()

相關問題