循环迭代不会像它应该的那样工作

时间:2017-08-20 18:04:45

标签: c# mysql loops iteration

labels[i]外,一切正常。循环总是写在htmlLabel1中,永远不在htmlLabel2等中。 为什么迭代不能在labels[i]下工作,但在Reader.GetValue(i)就好了?

MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT number FROM numbers ORDER BY RAND() LIMIT 2; ";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
    HtmlLabel[] labels = new HtmlLabel[] {
        htmlLabel1,
        htmlLabel2,
        htmlLabel3
    };
    for (int i = 0; i < Reader.FieldCount; i++)
    {
        labels[i].Text = Reader.GetValue(i).ToString();
        Console.WriteLine(Reader.GetValue(i).ToString());
    }
}
connection.Close();

1 个答案:

答案 0 :(得分:0)

只有一个字段,因此Reader.FieldCount每次都会返回1。 如果要循环遍历行,请使用以下代码

MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT number FROM numbers ORDER BY RAND() LIMIT 2; ";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
int i=0;
HtmlLabel[] labels = new HtmlLabel[] {
    htmlLabel1,
    htmlLabel2,
    htmlLabel3
};
while (Reader.Read())
{

    //for (int i = 0; i < Reader.FieldCount; i++)
    //{
        labels[i].Text = Reader[0].ToString();
        Console.WriteLine(Reader[0].ToString());
    //}
    i +=1;
}
connection.Close();