当我按下按钮时,应用程序会给我一个错误"索引超出范围"

时间:2013-01-13 17:28:14

标签: asp.net sql-server

在这段代码中,我动态创建了一个复选框,用我的数据库填充数据。

我的意图是当我按btnProba按钮仅显示所选复选框的文本属性时。但它在这一行中给我一个错误,说索引超出范围!我无法解释原因。

lblProba.Text = myche[0];

public partial class FormEGN : System.Web.UI.Page
{
        string mynewstring;
        List<string> myche = new List<string>();
        CheckBoxList mycheckbox = new CheckBoxList();
        protected void Page_Load(object sender, EventArgs e)
        {
            mynewstring = (string)Session["id2"];

           // lblProba.Text = mynewstring;
            if(!IsPostBack)
            {
                ddlNumberTourists.Items.Add("1");
                ddlNumberTourists.Items.Add("2");
                ddlNumberTourists.Items.Add("3");
            }
        }

        protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
        {
            int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);

            for (int i = 0; i < numTourists; i++)
            {
                Label myLabel = new Label();
                myLabel.ID = "lblAccomodation" + (i + 1).ToString();
                myLabel.Text = "Настаняване Турист" + (i + 1).ToString();
                Page.FindControl("form1").Controls.Add(myLabel);
                DropDownList myDropDownList = new DropDownList();
                myDropDownList.ID = "ddlTourist" + i.ToString();
                Page.FindControl("form1").Controls.Add(myDropDownList);
                Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));

                string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
                string query =
          "SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand(query, conn);

                try
                {
                    conn.Open();
                    SqlDataReader rd = cmd.ExecuteReader();
                    int s = 0;

                    while (rd.Read())
                    {
                        // CheckBox myCheckbox = new CheckBox();
                        //   myCheckbox.ID = "ckbExtraCharge" + i.ToString() + s.ToString();
                        // myCheckbox.Text = rd["Extra_Charge_Description"].ToString();
                        //  Page.FindControl("form1").Controls.Add(myCheckbox);
                        //  Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
                        //  s++;

                        mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
                        mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
                        Page.FindControl("form1").Controls.Add(mycheckbox);

                        if (mycheckbox.Items[s].Selected == true)
                        {  
                            myche.Add(mycheckbox.Items[s].Text);
                        }
                        s++;
                    }
                }
                catch (Exception ex)
                { }
            }
        }    

        protected void btnProba_Click(object sender, EventArgs e)
        {
            lblProba.Text = myche[0];
        }

        protected void btnReserve_Click(object sender, EventArgs e)
        { 
            string num = Request.QueryString["ExcursionID"];
            Response.Redirect(String.Format("ClintsInformation.aspx?Excursiondate_ID={0}",num));
        }
    }
}

2 个答案:

答案 0 :(得分:0)

函数ddlNumberTourists_SelectedIndexChanged是设置myche何时找到一些被选中的函数,但数据在第二次调用时丢失,其中是

 protected void btnProba_Click(object sender, EventArgs e)
        {
            // here is the issue
            lblProba.Text = myche[0];
        }

这两个电话发生在不同的帖子上。

您需要点击按钮上的ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)而不是每次更改下拉列表,例如我将其重命名为CheckWhatIsSelected(),这是代码:

protected void CheckWhatIsSelected()
        {
            int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);

            for (int i = 0; i < numTourists; i++)
            {
                Label myLabel = new Label();
                myLabel.ID = "lblAccomodation" + (i + 1).ToString();
                myLabel.Text = "??????????? ??????" + (i + 1).ToString();
                Page.FindControl("form1").Controls.Add(myLabel);
                DropDownList myDropDownList = new DropDownList();
                myDropDownList.ID = "ddlTourist" + i.ToString();
                Page.FindControl("form1").Controls.Add(myDropDownList);
                Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));

                string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
                string query =
          "SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand(query, conn);

                try
                {
                    conn.Open();
                    SqlDataReader rd = cmd.ExecuteReader();
                    int s = 0;

                    while (rd.Read())
                    {
                        // CheckBox myCheckbox = new CheckBox();
                        //   myCheckbox.ID = "ckbExtraCharge" + i.ToString() + s.ToString();
                        // myCheckbox.Text = rd["Extra_Charge_Description"].ToString();
                        //  Page.FindControl("form1").Controls.Add(myCheckbox);
                        //  Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
                        //  s++;

                        mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
                        mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
                        Page.FindControl("form1").Controls.Add(mycheckbox);

                        if (mycheckbox.Items[s].Selected == true)
                        {  
                            myche.Add(mycheckbox.Items[s].Text);
                        }
                        s++;
                    }
                }
                catch (Exception ex)
                { }
            }
        }    

     protected void btnProba_Click(object sender, EventArgs e)
            {
                CheckWhatIsSelected();
                if(myche.Count > 0)
                   lblProba.Text = myche[0];
                else
                   lblProba.Text = "Non selected";
            }

另一种可能的解决方案是将myche保存在viewstate上。

答案 1 :(得分:0)

使用ViewState的其他解决方案。您可以使用ViewState存储您的选择,并在回发后使用它。不要忘记在ddlNumberTourists_SelectedIndexChanged

上清除您的列表
List<string> myche
{
    get
    {
        if (!(ViewState["cMyChe"] is List<string>))
        {
            // need to fix the memory and added to viewstate
            ViewState["cMyChe"] = new List<string>();
        }

        return (List<string>)ViewState["cMyChe"];
    }
}

 protected void btnProba_Click(object sender, EventArgs e)
{
    // double check if have something on the list
    if(myche.Count > 0)
       lblProba.Text = myche[0];
    else
       lblProba.Text = "Non selected";
}