2

我正在使用 Visual Studio 2010,并report.mdf在我的项目中添加了一个新项目作为数据库;我创建了一个表Table1,并手动将一条记录添加到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();
4

1 回答 1

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);
    }
}
于 2013-05-06T20:20:18.387 回答