【发布时间】:2011-08-02 13:28:07
【问题描述】:
如何将SqlDataReader 返回的值添加到通用列表?我有一种方法,我使用SqlDataReader 从Category 表中获取CategoryID。我想将所有CategoryID 添加一个通用列表。
这不起作用,因为它只返回一个categoryID,这是最后一个。我想将所有categoryID 添加到列表中,然后返回它们。
我该怎么做?
SqlConnection connection = null;
SqlDataReader reader = null;
SqlCommand cmd = null;
try
{
connection = new SqlConnection(connectionString);
cmd = new SqlCommand("select CategoryID from Categories", connection );
connection.Open();
List<int> catID = new List<int>();
dr = cmd.ExecuteReader();
while (dr.Read())
{
catID.Add(Convert.ToInt32(dr["CategoryID"].ToString()));
}
}
finally
{
if (connection != null)
connection.Close();
}
return catID;
【问题讨论】:
-
你有一个名为
catId的字段吗? -
在连接、命令和阅读器周围使用 using 语句!
标签: c# sql sqldatareader