[英]How do I extract data from a table using a SqlDataReader when the number of rows are not predetermined?
I have an application that will allow a user to take a survey on 40 different fruit types stored in a table. 我有一个应用程序,允许用户对存储在表中的40种不同水果类型进行调查。 The first screen allows the user to choose from a list of fruit he/she would have tried out.
第一个屏幕允许用户从他/她本来可以尝试的水果列表中进行选择。 While the user is selecting their fruit type I am getting the ID of the fruit in the table for a SQL comparison and storing the different amount of fruit types they selected.
当用户选择他们的水果类型时,我在表中获取水果的ID以进行SQL比较,并存储他们选择的不同数量的水果类型。
string strFruits = string.Empty;
foreach (System.Web.UI.WebControls.ListItem li in chkFruits.Items)
{
if (li.Selected == true)
{
strFruits += "'" + li.Value + "'" + ",";
countFruits += 1;
ActiveCount += 1;
}
}
I also have a List Object which I use (with the help of a reader) to pull the fruit types from the database once I have been given the IDs. 我还有一个List对象,一旦获得ID,就可以使用该对象(在读者的帮助下)从数据库中提取水果类型。 How do I use the List object and the reader to pull an undetermined amount from my table.
如何使用列表对象和阅读器从表中提取未确定的金额。 Normally, If I knew that I only wanted to pull the top three rows I could do:
通常,如果我知道我只想排在前三行,我可以这样做:
SqlCommand cmd3 = new SqlCommand(@"SELECT [ID], [Fruits] from [my_tastyfruits]", conn1);
using (SqlDataReader reader1 = cmd3.ExecuteReader())
{
while (reader1.Read())
{
MyFruits foo = new MyFruits();
foo.ID = reader1.GetInt32(0);
foo.Fruits = reader1.GetString(1);
myFruits.Add(foo);
}
//assign fruits here
strFruit1 = MyFruits[0].Fruits;
strFruit2 = MyFruits[1].Fruits;
strFruit3 = MyFruits[2].Fruits;
...
}
However since the count is determined by the user I am not sure how to extract the data via the reader. 但是,由于计数是由用户确定的,因此我不确定如何通过读取器提取数据。
Leave the data in the ( MyFruit
) Collection and deal with it appropriately later. 将数据保留在(
MyFruit
) 集合中,并在以后进行适当处理。
For example, iterate it for display as needed; 例如,根据需要对其进行迭代显示。
foreach (var fruits in MyFruits) {
Console.WriteLine(fruits.Fruits);
}
It is not possible to assign an arbitrary sized list to an arbitrary number of variables at run-time: the number and types of variables are fixed when the code is compiled. 这是不可能的任意大小的列表分配给在运行时变量的任意数目:当代码被编译的数量和类型的变量是固定的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.