【问题标题】:How to get Selected value of dynamically created checkboxlist in for loop如何在for循环中获取动态创建的复选框列表的选定值
【发布时间】:2011-08-05 22:16:51
【问题描述】:

我有一个动态创建的复选框列表数组,现在我想在 for 循环中获取复选框列表的选定值,我的代码如下

protected void OnbtnNext1_Click(object sender, EventArgs e) {

        for (int i = 0; i < this.cbCountry.Items.Count; i++)
        {
            if (cbCountry.Items[i].Selected)
            {
                itemsCountry.Add(cbCountry.Items[i].Value);
                countCountry++;
            }
        }

        PopulateWaveCheckBoxes(itemsCountry);
        this.pnlWave.Visible = true;
    }


    private void PopulateWaveCheckBoxes(ArrayList items)
    {
        Label[] lbls = new Label[items.Count];
        CheckBoxList cblWave = new CheckBoxList[items.Count];

        for (int i = 0; i < items.Count; i++)
        {
            lbls[i] = new Label();
            lbls[i].Text = items[i].ToString();
            cblWave[i] = new CheckBoxList();
            cblWave[i].ID = "Checkbox" + i.ToString();
            cblWave[i].Items.Add(new ListItem("Wave 1"));
            cblWave[i].Items.Add(new ListItem("Wave 2"));
            cblWave[i].Items.Add(new ListItem("Wave 3"));
            cblWave[i].Items.Add(new ListItem("Wave 4"));
            this.pnlWave.Controls.Add(lbls[i]);
            this.pnlWave.Controls.Add(cblWave[i]);
            this.pnlWave.Controls.Add(new LiteralControl("<br>"));
        }
    }

    protected void OnbtnNext2_Click(object sender, EventArgs e)
    {

        itemsWave = new ArrayList[countCountry];
        for (int j = 0; j < countCountry; j++)
        {
            itemsWave[j] = new ArrayList();
            for (int i = 0; i < 4; i++)
            {
                if (cblWave[j].Items[i].Selected) // Here i want to get the values
                {
                    itemsWave[j].Add(cblWave[j].Items[i].Value);
                }
            }
            PopulateColorCheckBoxes(itemsWave[j], j);
        }
    }

【问题讨论】:

    标签: asp.net dynamic c#-4.0 selecteditem checkboxlist


    【解决方案1】:

    您应该将您的CheckBoxList cblWave 声明为类变量:

    CheckBoxList cblWave;
    

    然后在你的PopulateWaveCheckBoxes 中你应该实例化并填充它:

    private void PopulateWaveCheckBoxes(ArrayList items){
    Label[] lbls = new Label[items.Count];
    cblWave = new CheckBoxList[items.Count];
    

    【讨论】:

    • 感谢 Dampe,但我已经将它声明为类变量。我正在阅读一篇文章以在运行时保留复选框列表的值,可以通过 ViewState。但是 ViewState 的问题是,它不允许不可序列化的对象。由于 CheckBoxList 是不可序列化的,我现在必须标记为可序列化,但为此,我可能需要为复选框列表创建另一个可序列化类。但我不知道怎么做,或者这是唯一的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2020-11-22
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    相关资源
    最近更新 更多