在动态创建的表中获取动态控件值

时间:2013-05-02 04:39:24

标签: c# asp.net dynamic

我正在尝试读取表格单元格中的复选框值,但是在通过按钮提交进行回发时,整个表格都会消失。如果在发生page_load时它不是回发,我只创建表,并且我认为表一旦创建就会在回发中持续存在。

如何使用单元格的复选框值保留整个表格?感谢。

protected void CreateTable()
{
    int rowCnt; // Total number of rows.
    int rowCtr; // Current row count.
    int cellCtr; // Total number of cells per row (columns).
    int cellCnt; // Current cell counter.

    rowCnt = 6;
    cellCnt = 8;

    string baseStartTime = (ConfigurationManager.AppSettings["DEFAULTBASESELLSCHEDULETIME"]);
    int incrementInMins = Convert.ToInt32((ConfigurationManager.AppSettings["DEFAULTBASESELLSCHEDULETIME_INCREMENT"]));

    DateTime tempTimeFrom = Convert.ToDateTime(baseStartTime); // Converts only the time
    tempTimeFrom = tempTimeFrom.AddMinutes(-incrementInMins);
    // Because the very first loop will add 30 mins right away 

    for (rowCtr = 1; rowCtr <= rowCnt; rowCtr++)
    {
        tempTimeFrom = tempTimeFrom.AddMinutes(incrementInMins);
        DateTime tempTimeTo = tempTimeFrom.AddMinutes(incrementInMins);

        string timeFrom = tempTimeFrom.ToString("hh:mm tt");
        string timeToClassName = tempTimeTo.ToString("hh:mm");
        string timeTo = tempTimeTo.ToString("hh:mm tt");

        // Create a new row and add it to the table.
        TableRow tRow = new TableRow();
        tblSellSchedule.Rows.Add(tRow);
        for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++)
        {
            // Create a new cell and add it to the row.
            TableCell tCell = new TableCell();
            tRow.Cells.Add(tCell);

            if (cellCtr == 1) // We need the time for the first column of every row
            {
                tCell.Controls.Add(new LiteralControl(timeFrom + "-" + timeTo));
                tCell.CssClass = timeToClassName;
            }
            else
            {
                // tCell.Controls.Add(new LiteralControl("Select"));
                CheckBox chkbox = new CheckBox();

                chkbox.ID = tblSellSchedule.Rows[rowCtr - 1].Cells[0].CssClass + (cellCtr - 1);
                tCell.Controls.Add(chkbox);
                //  tCell.ID = (cellCtr - 1).ToString();
                tCell.CssClass = (cellCtr - 1).ToString();
            }
        }
    }
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
    foreach (TableRow row in tblSellSchedule.Rows)
    {
        foreach (TableCell cell in row.Cells)
        {
            foreach (CheckBox c in cell.Controls.OfType<CheckBox>())
            {
                if (c.Checked)
                {
                    var idVal = c.ID;
                }
            }
        }
    }
}

protected void Page_Load(object sender, EventArgs e)     
{
    if (!Page.IsPostBack)
    {
        CreateTable();
    }
}

1 个答案:

答案 0 :(得分:3)

我认为你应该在page_Init()中调用你的方法CreateTable()。 因为在每个帖子上,你创建的每个DOM内容都将消失。所以你必须在每个帖子上再次创建它,所以你必须在page_Load()之前访问的page_Init()中进行这种重新创建。