Search code examples
c#mysqllistphpmyadmindatareader

Using lists to retrieve information from MySql Database getting Exception "Index was outside the bounds of the array."


I have this C# code:

    public static Member searchMember(int memberID)
    {
        Member member = null; ;
        MySqlDataReader dataReader = null;
        string query = "SELECT * FROM MEMBER WHERE memberID='" + memberID + "'";
        MySqlConnection connection = new MySqlConnection(conn);

        try
        {
           connection.Open();
           MySqlCommand cmd = new MySqlCommand(query, connection);

           // Create a data reader and Execute the command
           dataReader = cmd.ExecuteReader();

           //Read the data and store them in the list
           while (dataReader.Read())
           {
              member = new Member();
              member.MemberID = Convert.ToInt32(dataReader[0]);
              member.UserName = dataReader[1].ToString();
              member.Password = dataReader[2].ToString();
              member.Name = dataReader[3].ToString();
              member.Surname = dataReader[4].ToString();
              member.MF1 = dataReader[5].ToString();
              member.DOB1 = dataReader[6].ToString();
              member.Address = dataReader[7].ToString();
              member.PhoneNo = dataReader[8].ToString();
              member.EMail = dataReader[9].ToString();
           }

           //return list to be displayed
           return member;
        }

        catch(Exception)
        {
           throw;
        }

        finally
        {
           //close Data Reader
           dataReader.Close();

           //close Connection
           connection.Close();
        }
     }

What this method do is that it retrieves data from a mysql database table and stores it in a list. For some reason when this method is begin executed I'm receiving an exception with details: "Index was outside the bounds of the array.". I don't know if I provided enough information but please request any other information if you don't have enough.

Thanks!


Solution

  • It seems your dataReader doesn't have as much value as your code use. Are you sure you have 10 columns in your table Member ?