Reputation: 13875
I have the following method which is used to populate a DAO from the database. It performs 3 reads - one for the primary object, and 2 for some translations.
public bool read(string id, MySqlConnection c)
{
MySqlCommand m = new MySqlCommand(readCommand);
m.Parameters.Add(new MySqlParameter("@param1", id));
m.Connection = c;
MySqlDataReader r = m.ExecuteReader();
r.Read();
accountID = Convert.ToInt32(r.GetValue(0).ToString());
...
comment = r.GetValue(8).ToString();
r.Close();
m = new MySqlCommand(getAccountName);
m.Parameters.Add(new MySqlParameter("@param1", accountID));
m.Connection = c;
r = m.ExecuteReader();
r.Read();
account1Name = r.GetValue(0).ToString();
r.Close();
m = new MySqlCommand(getAccountName);
m.Parameters.Add(new MySqlParameter("@param1", secondAccountID));
m.Connection = c;
r = m.ExecuteReader();
r.Read();
account2Name = r.GetValue(0).ToString();
r.Close();
return true;
}
On the line account2Name = r.GetValue(0).ToString();
I get the following error:
Invalid attempt to access a field before calling Read()
I don't understand what the problem is - the previous line calls read!
Upvotes: 1
Views: 1099
Reputation: 116538
account1Name = r.GetValue(0).ToString();
. Maybe you want to check the return value of r.Read()
to see if there are any rows first. The error could be interpreted as "Attempted to access a field without data"...ExecuteScalar()
method instead of ExecuteReader()
.Upvotes: 1
Reputation: 5917
That seems to be working earlier in your code. Are you sure there is a value to read there (i.e. is your query returning 0 rows or null or something else that can't be converted to a string?)
Upvotes: 3