我正在使用一个列表并从数据库填充它。
public List<HimHer.Models.Stories> GetAllImages()
{
try
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
{
SqlCommand sqlcom = new SqlCommand("Select * from Images", con);
SqlDataAdapter adp = new SqlDataAdapter(sqlcom);
con.Open();
SqlDataReader dt = sqlcom.ExecuteReader();
List<HimHer.Models.Stories> list = new List<Stories>();
Stories st = new Stories();
while (dt.Read())
{
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
}
list.Add(st);
return list;
}
}
catch (Exception ex)
{
throw ex;
}
}
Stories模型只有2个属性,例如Story,Image。
但是我的列表只返回最后一行,为什么?我想让它返回所有行。
答案 0 :(得分:9)
因为您只在列表中添加一个元素:
Stories st = new Stories();
while (dt.Read())
{
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
}
list.Add(st);
相反,将每个元素添加到列表中:
while (dt.Read())
{
Stories st = new Stories();
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
list.Add(st);
}
旁注:您的catch
块是多余的,实际上对异常处理和调试有害。你应该完全删除它。
答案 1 :(得分:0)
在while中添加列表:
public List<HimHer.Models.Stories> GetAllImages()
{
try
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
{
SqlCommand sqlcom = new SqlCommand("Select * from Images", con);
SqlDataAdapter adp = new SqlDataAdapter(sqlcom);
con.Open();
SqlDataReader dt = sqlcom.ExecuteReader();
List<HimHer.Models.Stories> list = new List<Stories>();
Stories st;
while (dt.Read())
{
st= new Stories();
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
list.Add(st);
}
return list;
}
}
catch (Exception ex)
{
throw ex;
}
}
由于在while之外有列表,因此只会添加最后存储的值
答案 2 :(得分:0)
这里的问题是你的“添加”方法是在while循环执行完毕后放置的。
public List<HimHer.Models.Stories> GetAllImages()
{
try
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
{
SqlCommand sqlcom = new SqlCommand("Select * from Images", con);
SqlDataAdapter adp = new SqlDataAdapter(sqlcom);
con.Open();
SqlDataReader dt = sqlcom.ExecuteReader();
List<HimHer.Models.Stories> list = new List<Stories>();
while (dt.Read())
{
Stories st = new Stories();
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
list.Add(st);
}
return list;
}
}
catch (Exception ex)
{
throw ex;
}
}