【发布时间】:2013-03-10 07:20:08
【问题描述】:
在我的代码中,我有一个 CheckboxList,我动态添加它的项目!我想要的是保存文本,但只能从会话中的 checked CheckBoxes 中保存,因为我将在下一个表单中需要它!
所以我想制作一些文本,如您所见,我将选中复选框中的文本保存在名称为 myche 的列表中,但是当我按下按钮查看此列表的第一项时 - 此代码 @987654323 @ 给了我一个例外“索引超出范围”。看来我的清单是空的。
public partial class FormEGN : System.Web.UI.Page
{
string mynewstring;
//List<List<string>> mycheckedList = new List<List<string>>();
List<string> myche = new List<string>();
CheckBoxList mycheckbox = new CheckBoxList();
protected void Page_Load(object sender, EventArgs e)
{
mynewstring = (string)Session["id2"];
if(!IsPostBack)
{
ddlNumberTourists.Items.Add("1");
ddlNumberTourists.Items.Add("2");
ddlNumberTourists.Items.Add("3");
}
}
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));
}
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())
{
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++;
}
}//End of try
catch (Exception ex)
{ }
Session["chk"] = myche;
}//end of for
}
}
【问题讨论】:
-
请正确格式化您的代码,删除无意义的空行。
-
@Lion - 你有足够的声誉进行编辑并向 OP 展示正确的方法。
-
请仅发布 相关 代码 - 发布所有这些代码只会让人难以找出问题 - 诸如导致错误和相关代码。我建议遵循sscce 的指导方针
-
空的 catch 块是一种非常糟糕的编码习惯——不要吞下这样的异常。
标签: asp.net