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"));
values[countValues] = reader2.GetString("textinfo");
countValues++;
}
countValues = 0;
connection.Close();
}
}
}
Mohamed Azarudeen ZRank #297 · 8.5K reputationPosted Jul 4, 2023, 1:23 PM EDT
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:public static List values = new List(); // Initialize the List 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.Add(reader2.GetString("textinfo")); // Add values to the List } connection.Close(); } } } // If you need the values as an array, you can convert the List to an array: string[] valuesArray = values.ToArray();Amit MohantyRank #112 · 20K reputationPosted Jul 5, 2023, 1:54 AM EDT
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()) { // Get the count of rows returned by the query int rowCount = (int)reader2["RowCount"]; values = new string[rowCount]; // Initialize the values array with the appropriate size while (reader2.Read()) { listBoxMeasurement.Items.Add(reader2.GetString("textinfo")); values[countValues] = reader2.GetString("textinfo"); countValues++; } countValues = 0; connection.Close(); } } }