如何在c#中的master的子页面中动态创建控件?

时间:2015-06-01 07:21:56

标签: c#

我已成功动态创建控件但是当我应用母版页然后抛出错误“对象引用未设置为对象的实例”。 下面是我的代码。

protected void GenerateTableOnDelete(int rowsCount, int deleteID)
        {
            rowsCount--;
            Table table = new Table();
            table.ID = "Table1";
            PlaceHolder1.Controls.Add(table);
            const int colsCount = 6;
            TableHeaderRow header = new TableHeaderRow();
            TableHeaderCell headerTableCell1 = new TableHeaderCell();
            headerTableCell1.Text = "Item Name";
            header.Cells.Add(headerTableCell1);                
            table.Rows.Add(header);
            for (int i = 0, k = 0; i < rowsCount; i++)
            {
                if (i < deleteID)
                    k = i;
                else
                    k = i - 1;
                if (deleteID != i)
                {
                    TableRow row = new TableRow();
                    row.ID = "Row_" + k;
                    for (int j = 0; j < colsCount; j++)
                    {
                        if (j == colsCount - 6)
                        {
                            TableCell cell = new TableCell();
                            DropDownList ddl = new DropDownList();                           
                            ds = fetchStates();
                            ddl.DataSource = ds.Tables[0];
                            ddl.DataValueField = "EmpId";
                            ddl.DataTextField = "EmpName";
                            ddl.DataBind();
                            ddl.ID = "DropDownListRow_" + k + "Col_" + j;
                            cell.Controls.Add(ddl);
                            row.Cells.Add(cell);
                        }

                    }
                    table.Rows.Add(row);
                }
            }
            SetPreviousDataOnDelete(rowsCount, colsCount, deleteID);
            ViewState["RowsCount"] = rowsCount;
        }

此行获取错误第49行:Table table = (Table)this.Page.FindControl("PlaceHolder1").FindControl("Table1"); // **** if (table != null) {

private void SetPreviousData(int rowsCount, int colsCount)
        {
            Table table = (Table)this.Page.FindControl("ContentPlaceHolder1").FindControl("Table1"); // ****         if (table != null) {
            for (int i = 0; i < rowsCount; i++)
            {
                for (int j = 0; j < colsCount; j++)
                {
                    if (j == colsCount - 6)
                    {
                        //Extracting the Dynamic Controls from the Table
                        DropDownList ddl = (DropDownList)table.Rows[i+1].Cells[j].FindControl("DropDownListRow_" + i + "Col_" + j);
                        //Use Request object for getting the previous data of the dynamic textbox
                        ddl.Text = Request.Form["DropDownListRow_" + i + "Col_" + j];//*****                 }                
                    }
}
            }
        }

0 个答案:

没有答案