动态添加的复选框在使用c#的asp.net中不起作用?

时间:2013-01-14 06:29:42

标签: asp.net checkbox dynamic-controls

我在asp.net页面中添加了多个复选框:

 public static CheckBox[] chck;

on pageload:

 protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
      con.Open();
        SqlCommand cmd = new SqlCommand("select count(CompanyName) from Stock_Company");
        cmd.Connection = con;
        comno = Convert.ToInt32(cmd.ExecuteScalar());
         con.Close();

        chck = new CheckBox[comno];
    }
 }

现在我有一个生成复选框的功能:

   public void generatecheckbox1()
{

    con.Open();
    SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
    cmd.Connection = con;
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    DataTable dt = ds.Tables[0];
    con.Close();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        chck[i] = new CheckBox();
        chck[i].ID = "chck" + Convert.ToString(i);
        chck[i].Text = dt.Rows[i]["CompanyName"].ToString();
        pnlcom1.Controls.Add(chck[i]);
        pnlcom1.Controls.Add(new LiteralControl("<br />"));
    }
  }

我在组合框事件中调用它:

 protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ddluserwebser.SelectedItem.Text == "Custom")
    {
        generatecheckbox1();
    }
 }

就这一切工作正常而言...但是在按钮单击中我想获取选择复选框的文本,我没有得到

我做了一个功能:

   public string getbsecompany()
{
    string companyname = "";
    string bsetricker = "";
    con.Open();
    SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
    cmd.Connection = con;
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    DataTable dt = ds.Tables[0];
    con.Close();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        if (chck[i].Checked == true)     **THE PROBLEM IS HERE**
        {
            companyname = chck[i].Text;
            con.Open();
            SqlCommand cmdd = new SqlCommand("select BSETickerCode from Stock_Company where CompanyName='" + companyname + "'");
            cmdd.Connection = con;
            bsetricker += bsetricker + "+" + cmdd.ExecuteScalar();
            con.Close();
        }
    }

    return bsetricker;
}

我在这里叫它:

  protected void btnusersave_Click(object sender, EventArgs e)
{
    string bsetricker = "";
    bsetricker = getbsecompany();
}

问题是我没有收到复选框的文字。当我正在检查if (chck[i].Checked == true)时,我会{get} false并检查所有复选框。 我现在应该怎么做? 任何帮助

1 个答案:

答案 0 :(得分:0)

如果要在页面中显示动态控件,则每次都应将其添加到On_Init()页面中。 否则,你无能为力。 另外,最好不要使用静态值来包含checkBox List,当多用户访问同一页面时会引起问题。您可以将它们保存在会话中或尝试this.Form.FindControls()