-3

i can get record from database and take its into objects

for (int i = 0; i < selectedFishes.Length; i++)
{
    string stm = "SELECT * FROM Data WHERE name='" + selectedFishes[i] + "'";
    SQLiteCommand cmd = new SQLiteCommand(stm, conn);
    SQLiteDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        fish[i] = new fish(rdr.GetString(0), rdr.GetDouble(1), rdr.GetDouble(2), rdr.GetDouble(3), rdr.GetDouble(4));
        Console.WriteLine(fish[i].name + " " + fish[i].value1 + " " + fish[i].value2 + " " + fish[i].value3 + " " + fish[i].value4);//it can be displayed into console
    }
}

MessageBox.Show(selectedFishes.Length.ToString()+" "+fish.Length.ToString());//results are same if the value >5 cant be displayed
for (int i = 0; i < fish.Length; i++)
{
   Console.WriteLine(fish[i].name + " " + fish[i].value1 + " " + fish[i].value2 + " " + fish[i].value3 + " " + fish[i].value4);

}

why cant be displayed? the error is"Object reference not set to an instance of an object" thanks before

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79

3 Answers3

3

I'm taking a wild guess and say that selectedFishes.Length is probably not equal to fish.Length. To be precise the former is most likely less than the latter.

Which means you only create objects for indices 0 to selectedFishes.Length-1 and then try to access index selectedFishes.Length which is still null and cause that exception.

To fix this you can change the upper bound of the second for loop or do a null check inside it.

Edit: and do you really want that while loop inside the first for loop? i doesn't change inside the while loop so you keep adding fish objects into the same array index.

Dirk
  • 10,668
  • 2
  • 35
  • 49
1

I'd say always in NullReferenceException try to ToString() each object that you expect to have a value.

0

Add a breakpoit to the second console writeline by pressing f9. Press f5. Let your program hit the breakpoint. Check ifname or value1-4 is null. Add code to handle null values.

  • If you cannot reach the second console writeline where you told us the error occurs then then there must be something wrong earlier. Add abreakpoint some lines above and step through the code investigating the contents of your objects. You should read some introduction about debugging in visual studio. You will need debugging with a propability of 100%. –  May 26 '13 at 09:33