2

I am getting the output that I do not want to get. I think my code is correct however there might be something I missed.

C# Code:

try
 {
string mydbConnection = "datasource=localhost;port=3306;username=root;password=Greenford123;";
MySqlConnection connDB = new MySqlConnection(mydbConnection);
MySqlCommand cmdDataBase = new MySqlCommand("SELECT * FROM project.student", connDB);
MySqlDataReader DBReader;
connDB.Open();
DBReader = cmdDataBase.ExecuteReader();
while (DBReader.Read())
{
List<string> mylist = new List<string>();
mylist.Add(DBReader.ToString());

foreach (var item in mylist)
{
MessageBox.Show("The details are " + item);
}  
}
connDB.Close();
}
        catch(Exception ex)
        {
            MessageBox.Show("Error! " + ex);
        }

What I want to do is store contents from database into a list so that I could do operations on it. Then I want to output the list however the output is not the "string" or data. The output I get is :

OUTPUT: "the details are MySQL.Data.MySqlClient.MySqlDataReader"

  • You could use EF, and then something like `if (myObject.firstName == myEntity.firstName) { doSomething; } ` – Austin T French Feb 24 '17 at 23:15
  • Here is an example to make list from datareader. http://stackoverflow.com/questions/8097978/using-datareader-for-filling-listt-in-c-sharp – Kay Lee Feb 24 '17 at 23:58
  • Possible duplicate of [using DataReader for filling List in c#](http://stackoverflow.com/questions/8097978/using-datareader-for-filling-listt-in-c-sharp) – Dour High Arch Feb 25 '17 at 00:37

1 Answers1

0

The line:

        DBReader = cmdDataBase.ToString();

is wrong. It should be

        DBReader = cmdDataBase.ExecuteReader();
Slepz
  • 440
  • 3
  • 18
  • I am still getting the error. Cannot convert MySQL to string. The error I get is at the line 'mylist.Add(cmdDataBase);' – CsharpStudent Feb 24 '17 at 23:50
  • That's because cmdDataBase is a command and you're trying to add it to a list of strings. Look at the example section at the bottom of this page: https://dev.mysql.com/doc/dev/connector-net/html/T_MySql_Data_MySqlClient_MySqlDataReader.htm You need to be calling DBReader.Read() and DBReader.GetString(int length). – Slepz Feb 24 '17 at 23:57