我想在page_load的表的每一行的开头添加一些复选框:(我将它们添加到asp:placeholder中)

 protected void Page_Load(object sender, EventArgs e)
    {
        Table dtTable = new Table();
        TableHeaderRow dtHeaderRow = new TableHeaderRow();

        TableHeaderCell dtHeaderCheckbox = new TableHeaderCell();
        dtHeaderCheckbox.Controls.Add(dtHeaderCkBox);
        dtHeaderRow.Cells.Add(dtHeaderCheckbox);

        foreach (DataColumn col in _ds.Tables[0].Columns)
        {
                TableHeaderCell dtHeaderCell = new TableHeaderCell();
                dtHeaderCell.Text += col.ColumnName;
                dtHeaderRow.Cells.Add(dtHeaderCell);
        }

        dtTable.Rows.Add(dtHeaderRow);

        TableRow row;

        for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
        {

            row = new TableRow();

            TableCell dtCell = new TableCell();
            CheckBox ckBox = new CheckBox();
            ckBox.ID = "chkBox_" + _ds.Tables[0].Rows[i]["IDENTIFIER"].ToString();
            ckBox.AutoPostBack = false;
            ckBox.EnableViewState = false;

            dtCell.Controls.Add(ckBox);
            row.Cells.Add(dtCell);

            for (int j = 0; j < _ds.Tables[0].Columns.Count; j++)
            {
                TableCell cell = new TableCell();
                cell.Text = _ds.Tables[0].Rows[i][j].ToString();

                row.Cells.Add(cell);
            }

            dtTable.Rows.Add(row);

        }

        phUnconfirmedDiv.Controls.Add(dtTable);
    }


现在的问题是,当用户按下提交按钮(和回发)时,我无权访问我的复选框:

    protected void btnAccept_OnClick(object sender, EventArgs e)
    {
        List<CheckBox> chkList = new List<CheckBox>();
        foreach (Control ctl in form1.Controls)
        {
            if (ctl is CheckBox)
            {
                if (ctl.ID.IndexOf("chkBox_") == 0)
                {
                    chkList.Add((CheckBox)ctl);
                }
            }
        }
        ScriptManager.RegisterStartupScript(this, GetType(), "event", "alert('" + chkList.Count + "');", true);
    }

最佳答案

一旦动态生成的控件在视图中呈现,它们就会失去其状态。对于您来说,要在后台代码中再次访问它们,则当您回发时,您将不得不重新创建它们,之后便可以对其进行操作。

就获取复选框的选中值而言,您可以尝试这样的操作。这可能不准确,但是应该给出一个想法。

这将是您的复选框:

<input type="checkbox" id="yourId" name="selectedIds" value="someValue"/>


在您的代码背后:

value = Request.Form["selectedIds"];


希望这可以帮助。

关于c# - 在回发复选框后获取代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29767648/

10-11 20:09
查看更多