2013-05-06 124 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