0
    Sqlreader = cmd.ExecuteReader();        //sqlreader reading rows from a database table 
        displaytable disp = new displaytable(); //class with fields regno,name,age,sex

        List<displaytable> mystring = new List<displaytable>();

        while (SQLreader.Read())
        {

            disp._regno = reader.GetString(0);
            disp._name = reader.GetString(1);
            disp._age = reader.GetInt32(2);
            disp._sex = reader.GetString(3);
            mystring.Add(disp);
          //  mystring.Insert(i++, disp);
        }
        con.Close();
        return mystring;
                                    "

上面的代码用于将数据表中的行检索到列表中。样本行是 0001 aaaa 25 男性 0002 bbbb 26 女性 0003 cccc 28 男性,这是预期的输出。

但不幸的是,我的代码在某处是错误的,这给了我输出

         0003   cccc  28  male
         0003   cccc  28  male
         0003   cccc  28  male

我尝试了将所有行字段转换为字符串的列表,我得到了我需要的确切结果,但它不适用于类对象。请帮我。

4

1 回答 1

4

您正在更新和插入displaytable. 将对象的创建移入循环:

while (SQLreader.Read())
{
    displaytable disp = new displaytable();
    disp._regno = reader.GetString(0);
    disp._name = reader.GetString(1);
    disp._age = reader.GetInt32(2);
    disp._sex = reader.GetString(3);
    mystring.Add(disp);
}
于 2013-08-16T11:54:06.937 回答