我正在使用visual studio 2010,并将一个新项作为数据库添加到我的项目中;我创建了一个表report.mdf,并且手动向Table1添加了一条记录;但是当我尝试选择数据时,我无法执行此操作并出现此错误:
不存在数据时读取的尝试无效
这是我的代码:

SqlCommand objcomand = new SqlCommand();

SqlConnection con = new SqlConnection();
con.ConnectionString=@"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();

最佳答案

您必须使用DataReaderSqlDataReader.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);
    }
}

08-17 22:45