P
P
pimanov32020-08-11 10:11:53
SQL
pimanov3, 2020-08-11 10:11:53

How to fix the error "System.InvalidOperationException: "Invalid read attempt with no data.""?

How to fix the error "System.InvalidOperationException: "Invalid read attempt with no data.""?

using (SqlConnection connection = new SqlConnection(@"Data Source=...; Initial Catalog=Airlines; Integrated Security=True"))
{
    connection.Open();
    string sqlExpression = "SELECT ID FROM Users WHERE ID = 1";
    SqlCommand LoginData = new SqlCommand(sqlExpression, connection);
    SqlDataReader LoginReaderData = LoginData.ExecuteReader();

    if (LoginReaderData.HasRows)
    {
        object ID = LoginReaderData["ID"];

        Mail.Text = (string)ID;
    }
    else
    {
        MessageBox.Show("Пользователь не найден");
    }
}

5f324412d14e7659306673.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ayazer, 2020-08-11
@pimanov3

You are using the wrong reader.

SqlDataReader loginReaderData = LoginData.ExecuteReader();

 while (loginReaderData.Read())
 {
    var id = loginReaderData["ID"];
    // ...    
  }

But judging by the example - you don't need a reader at all, but you need https://docs.microsoft.com/en-us/dotnet/api/system...
string sqlExpression = "SELECT ID FROM Users WHERE ID = 1";
SqlCommand loginData = new SqlCommand(sqlExpression, connection);
var id = (string)loginData.ExecuteScalar();
//...

D
d-stream, 2020-08-11
@d-stream

Well, at least ask the reader to read the [next] line (Read()) and then extract the fields from the read line.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question