public Lword[] ListWord()
{

//返回一个Lword[]类型
Lword lword=new Lword();
ArrayList lwordList=new ArrayList();//数组用来存放信息string sql="select content,posttime,postman from word order by id";
using(SqlConnection conn=new SqlConnection(connstr))
       {
SqlCommand cmd=new SqlCommand(sql,conn);
try
{
conn.Open();
SqlDataReader reader=cmd.ExecuteReader();//
while(reader.Read())
{
        lword.PostTime=(DateTime)reader["posttime"];
lword.Content=(string)reader["content"];
lword.PostMan=(string)reader["postman"];
lwordList.Add(lword);
}
}
catch
{
throw;
}

}
Lword[] word=(Lword[])lwordList.ToArray(typeof(Lword));//word.length=5
return word;
} this.datalist.datasource=ListWord();
 this.datalist.databinde();
-------
数据库中共有5条记录,结果返回的5条记录都是数据库中最后一条,调试的时候,5条不同的纪录也都加到了lwordList中了
--提示:Lword.cs是个实体,罗列了数据库的几个字段属性。

解决方案 »

  1.   

    List<Lword > mylist = new List<Lword >;用泛型来的更简单些
      

  2.   

    ……List<Lword> mylist = new List<Lword>();
      

  3.   

    Lword lword;
    List<Lword> mylist = new List<Lword>();
    …………
    while(reader.Read())
    {
       lword = new Lword();
        …………
       mylist.Add(lword);
    }
    ……
      

  4.   

    你的lword是个对象的引用,每次赋值都会修改刚才的值,你可以这样注意加的注释public Lword[] ListWord()
    {

    //返回一个Lword[]类型
    Lword lword; //这里不要实例化
    ArrayList lwordList=new ArrayList();//数组用来存放信息string sql="select content,posttime,postman from word order by id";
    using(SqlConnection conn=new SqlConnection(connstr))
           {
    SqlCommand cmd=new SqlCommand(sql,conn);
    try
    {
    conn.Open();
    SqlDataReader reader=cmd.ExecuteReader();//
    while(reader.Read())
    {
    lword=new Lword(); //这里再实例化
            lword.PostTime=(DateTime)reader["posttime"];
    lword.Content=(string)reader["content"];
    lword.PostMan=(string)reader["postman"];
    lwordList.Add(lword);
    }
    }
    catch
    {
    throw;
    }

    }
    Lword[] word=(Lword[])lwordList.ToArray(typeof(Lword));//word.length=5
    return word;
    } this.datalist.datasource=ListWord();
     this.datalist.databinde();
      

  5.   

    把这个声明在循环里面
    Lword lword=new Lword();
      

  6.   

    lword=new Lword();
    放到
    while(reader.Read())
    {
    lword=new Lword();
    ……
    }
      

  7.   

    将lword申明为循环的局部变量
    try
    {
    conn.Open();
    SqlDataReader reader=cmd.ExecuteReader();//
    while(reader.Read())
    {
    Lword lword=new Lword();
    lword.PostTime=(DateTime)reader["posttime"];
    lword.Content=(string)reader["content"];
    lword.PostMan=(string)reader["postman"];
    lwordList.Add(lword);
    }
    }
    catch
    {
    throw;
    }