Question

int n =Count("SELECT COUNT(*) FROM information_schema.SCHEMATA");; //return 6

TreeNode[] db_name = new TreeNode[n];
MySqlCommand cmd = new MySqlCommand("show databases", connection);
MySqlDataReader dataReader = cmd.ExecuteReader();

for(i=0;i<n;i++)
{
    dataReader.Read();
    db_name[i] =  new TreeNode(dataReader[i].ToString());
}  

Why do I get IndexOutOfRangeException was unhandled,Index was outside the bounds of the array? If the Count() funciont return 6 that means there are 6 rows so 6 fields [0][1][2][3][4][5] I put a breakpoint in the for loop and I get the error at the second loop, when i=1. How can I fix that? I can't see the error. Thanks in advance.

Was it helpful?

Solution

The call to dataReader.Read() advances to the next available record.

When you call dataReader[i], you're probably trying to get a column that doesn't exist in your returned data. On the first iteration, dataReader[i] is trying to get the first column, but then on the second iteration it's just trying to get the second column, then third, etc. You're probably not returning 6 columns, so that's going to throw an exception.

You could try something like this instead, assuming that each record is just a string:

for(i=0; i<n; i++)
{
    dataReader.Read();
    db_name[i] =  new TreeNode(dataReader.GetString(0));

          // or use dataReader[0].ToString(), but don't change the index of 0
}

OTHER TIPS

Please try the following.

int i=0;
if (dataReader.HasRows)
{
    while (dataReader.Read())
    {
        db_name[i] =  new TreeNode(dataReader.GetString(0));          
    }
    i++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top