简体   繁体   中英

Index was outside the bounds of the array in c#

I want to insert MySqlDataReader read value into an array.but I get the exception "Index was outside the bounds of the array". Here is my code,

        string[] a = new string[1000];

        string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
        MySqlConnection mycon = new MySqlConnection(myconstring);
        string sql = "SELECT flag FROM sms_data_bankasia group by flag";
        MySqlCommand comd = mycon.CreateCommand();
        comd.CommandText = sql;
        mycon.Open();
        MySqlDataReader dtr = comd.ExecuteReader();
        count = 0;


        int i = 0;
            while (dtr.Read())
            {

                a[i] = dtr.GetValue(i).ToString();
                i++;

            }

What can I do.Any one can help me?

This looks suspicious to me:

a[i] = dtr.GetValue(i).ToString();

That means you're fetching column 0 of row 0, column 1 of row 1, column 2 of row 2 etc... but you've only got a single column ("flag").

I suspect you meant:

a[i] = dtr.GetValue(0).ToString();

That will still fail if there are more than 1000 rows though - it would be better to use a List<string> :

List<string> data = new List<string>();
while (dtr.Read())
{
    data.Add(dtr.GetValue(0).ToString()); // Or call GetString
}

Try cleaning your code a little and use a dynamically resizing List<T> to which you can add elements:

var result = new List<string>();
var myconstring = "SERVER=localhost;DATABASE=alicosms;UID=root;PASSWORD=;";
using (var con = new MySqlConnection(myconstring))
using (var cmd = con.CreateCommand())
{
    con.Open();
    cmd.CommandText = "SELECT flag FROM sms_data_bankasia group by flag";
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            result.Add(reader.GetString(reader.GetOrdinal("flag")));
        }
    }
}

string[] a = result.ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM