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?
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"));
values[countValues] = reader2.GetString("textinfo");
countValues++;
}
countValues = 0;
connection.Close();
}
}
}
Amit MohantyPosted Jul 5, 2023, 5:54 AM
Mohamed Azarudeen ZPosted Jul 4, 2023, 5:23 PM
Hi Ken
The error "Object reference not set to an instance of an object" occurs when you try to access a member of an object that is currently set to null (i.e., the object has not been instantiated or initialized). In your case, it seems like the
valuesarray is not initialized, causing the error.To fix this issue, you need to initialize the
valuesarray before using it. Since you don't know the exact number of values you'll be retrieving from the database, you can use aListto dynamically store the values and then convert it to an array if needed. Here's how you can modify your code to use aList: