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!
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?)