如何通过单击每个按钮获取数组中的下一个项目?

时间:2014-09-02 13:59:19

标签: c# sql sql-server arrays

我在SQL中有一个表,其中包含200多种不同的水果类型。我正在做的是创建一个应用程序,使用同一组问题调查用户关于这些不同的水果类型。该应用程序将首先要求用户从不同的水果类型中进行选择。我将用户选择的值和计数存储为单独的字符串和整数。然后我拿走他们选择的项目,每次按一下按钮就会显示一个。 已编辑的代码

protected string[] FruitList;

接下来我定义一个List来存储sql里面的值:

public class FruitList
{
    public int FruitID { get; set; }
    public string FruitName { get; set; }
}

然后在按钮单击中,我获取计数并根据用户从asp:CheckBoxList

中选择的值从数据库中检索数据
List<FruitList> FruitList = new List<FruitList>();
StringBuilder myFruits = new StringBuilder();
string strFruits = string.Empty;
foreach (System.Web.UI.WebControls.ListItem li in chkDepartments.Items)
{
    if (li.Selected == true)
    {
        strFruits += "'" + li.Value + "'" + ",";
        countFruits += 1;
        ActiveCount += 1;
    }
}

strFruits = strFruits.TrimEnd(',');
myFruits.Append("WHERE [id] IN(" + strFruits + ")");
if (countDeparments > 0)
{
    using (SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer2"].ConnectionString))
    {
        SqlCommand cmd1 = new SqlCommand("Select SELECT [ID], [Fruits] from [my_tastyfruits] " + myFruits, conn2);
        conn2.Open();
        using (SqlDataReader reader2 = cmd1.ExecuteReader())
        {
            while (reader2.Read())
            {
                FruitList fl = new FruitList();
                fl.DeptID = reader2.GetInt32(0);
                fl.FruitName = reader2.GetString(1);
                FruitList.Add(fl);
            }
        }
        foreach (var fruits in FruitList)
        {
            //string[] FruitList = {"\"" + fruits.FruitName + "\"",};
            Array.Resize(ref FruitList, countFruits);
            FruitList[countFruits - 1] = fruits.FruitName; 
        }
        ViewState["count"] = Convert.ToInt32(ViewState["count"]) + 1;
        txtNAC.Text = ViewState["count"].ToString();
        NAC = Convert.ToInt32(ViewState["count"]);
        Total = NAC - ActiveCount - 1;

        txtActiveCount.Text = FruitList[countFruits - 1];

        if (Total == 0)
        {
            NAC = 0;
            ActiveCount = 0;
            Response.Write("Congrats, The total is zero");
        }
        else if (Total >= 1)
        {
           Response.Redirect(Request.RawUrl);
        }                    
    }
}

目前此方法仅返回数组中的最后一项。它不会迭代数组中的第一个或中间项。

0 个答案:

没有答案