0

我通过这样做在我的 asp.net 页面中添加多个复选框:

 public static CheckBox[] chck;

在页面加载时:

 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)我刚开始false并且所有复选框都被选中。我现在该怎么办?任何帮助

4

1 回答 1

0

如果您希望动态控件显示在页面中,则每次都应在 On_Init() 中将动态控件添加到页面中。否则你什么也得不到。另外,最好不要使用静态值来包含复选框列表,当多个用户访问同一页面时会导致问题。您可以将它们保存在会话中或尝试 this.Form.FindControls()

于 2013-01-14T06:52:44.023 回答