-3

So basically here is the problem, I have tried many ways to fix it but none of them worked ! Error is getting at this line :Templist.Add((string)result["titre"];. Templist is the error !

private List<string> ReadNews()
{
    string SqlText = "SELECT * FROM nom_table"; 
    List<string> Templist; 
    MySqlConnection SqlConnection = new 
    MySqlConnection(TheConnectionString);
    MySqlCommand SqlCommand = new 
    MySqlCommand(SqlText,SqlConnection);


    MySqlDataReader result = SqlCommand.ExecuteReader();

    while (result.Read())
    {
        Templist.Add((string)result["titre"]);
    }

    return Templist;
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • What error? Post error message – barbsan Apr 24 '19 at 09:55
  • `NullReferenceException` does happen when you try to access to properties or methods of null objects. Your `Templist` is not assigned anothing (so it is null) – Cleptus Apr 24 '19 at 10:00
  • If your `nom_table` table has too many columns or columns with large amount of data, your query will take too much time. Consider changing your select to `SELECT titre FROM nom_table` – Cleptus Apr 24 '19 at 10:02
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Cleptus Apr 24 '19 at 10:07

3 Answers3

5

Because you haven't initialized the Templist, until you initialize/assign an instance the declared variable(Templist) will be null, and you are not able to add something to null that is what the error message says. The code should be :

List<string> Templist =  new List<string>();

One more thing I would like to add here is the usage of using for proper disposal of the objects, and also specified column names instead for *. Consider the modified snippets below:

private List<string> ReadNews()
{
    string SqlText = "SELECT titre FROM nom_table";
    List<string> Templist = new List<string>();
    using (SqlConnection SqlConnection = new MySqlConnection(TheConnectionString))
    {
        using (MySqlCommand SqlCommand = new MySqlCommand(SqlText, SqlConnection))
        {
            using (MySqlDataReader result = SqlCommand.ExecuteReader())
            {
                while (result.Read())
                {
                    Templist.Add((string)result["titre"]);
                }
            }

        }
    }
    return Templist;
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
4

Your Templist should be initialized before use. Change your declaration line to this:

List<string> Templist = new List<string>();
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Siavash Rostami
  • 1,883
  • 4
  • 17
  • 31
3

Templist is null, you haven't created an instance yet. Initialize:

List<string> Templist = new List<string>();
Th0rndike
  • 3,406
  • 3
  • 22
  • 42