Problem with string array?

ken76

Member
Joined
Nov 15, 2018
Messages
23
Programming Experience
5-10
I have a problem with this code, because it gives me following error message
Object reference not set to an instance of an object when I use the line
values[countValues] = reader2.GetString("textinfo"); in the code below.

Can someone help me?
C#:
    public static string[] values;
    int countValues = 0;
    using (var connection = new MySqlConnection(connString))
                {
                    connection.Open();
                    string query = "select * from showvalues where idvalue = '" + idStatus + "'";
                    using (var command2 = new MySqlCommand(query, connection))
                    {
                        using (var reader2 = command2.ExecuteReader())
                        {
                            while (reader2.Read())
                            {
                         
                               listBoxMeasurement.Items.Add(reader2.GetString("textinfo"));
                              [B] values[countValues] = reader2.GetString("textinfo");[/B]
                               countValues++;
                            }
                           countValues = 0;
                           connection.Close();
                         }
                    }
                }
 
The very first thing to do when a NullReferenceException is thrown is check each reference on the offending line to see which is null. I would imagine that it's going to be values because there's nothing in that code that indicates that you're assigning an object to that variable, so it will not have a value.
 
Apart from that, it doesn't look like you know how many elements you need anyway, so you probably ought to be using a List<string> rather than an array. You'll have to actually create an object of that type either way though.
 
Please.. Install the VS extension "EF Core Power Tools", reverse engineer your database, throw all your code away and replace it with:

C#:
var db = new Yourcontext()
foreach(var x in db.ShowValues.Where(sv => sv.Id == idStatus)){
  listBoxMeasurement.Items.Add(x.TextInfo);
}
 

Latest posts

Back
Top Bottom