0

I am having a problem is getting a value from mysql using c#. The connection string is right, but it throws the following error: Invalid attempt to access a field before calling Read()

Can anyone tell me the problem which occurs in the code below

            string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
            MySqlConnection connection = new MySqlConnection(strConnection);
            MySqlCommand command = connection.CreateCommand();
            MySqlDataReader reader;
            command.CommandText = "SELECT application_domain_name FROM `test`.`application_domains` WHERE idapplication_domains = " + reference;
            connection.Open();
            reader = command.ExecuteReader();

            lblApplicationDomain.Text = reader.GetString(0);

            connection.Close();
1

2 Answers 2

2

You must call reader.Read() before accessing the results. Before you do that, the reader 'cursor' will be placed before the first element. Placing the cursor before the first element will make the behavior consistent even if the result set is empty.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to call reader.Read() at least once. Like a normal SqlDataReader, the pattern is like so:

while(reader.Read())
{
    .. Do Stuff
}

while(sqlDataReader.MoveNext())
{
   .. Do Stuff
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.