在Page_Load()中动态创建的控件

本文关键字:动态 创建 控件 Page Load | 更新日期: 2023-09-27 18:22:20

我有一个关于在ASP.NET 4.0运行时创建控件的问题。我正在构建一个应用程序,在admin.aspx页面中,我有多个控件(DropDownLists),它们是用Sql数据库中的值动态创建的。我知道,要为动态创建的控件激发事件,我必须在Page_Load()Page_Init()中创建此控件。

我的项目有一个母版页,在里面我有一个1秒的计时器来更新时钟。这个计时器事件调用我的admin.aspx Page_Load()函数,所以我的方法创建动态控件,它每1秒调用一次——每1秒连接一次数据库,请查看下面的代码。

这样做很好吗?你能提出一些想法吗?

protected void Page_Load(object sender, EventArgs e)
{
    _SinopticBackgroundColor = ConfigurationManager.AppSettings["SinopticBackgroundColor"];
    panelContent.Style.Add("background-color", _SinopticBackgroundColor);
    Control c = GetControlThatCausedPostBack(this);
    if (c != null)
    {
        if (c.ID.Equals("btnManageCategory"))
            hfPageManage.Value = "category";
        else if (c.ID.Equals("btnManageDevices"))
            hfPageManage.Value = "device";
    }
    if (hfPageManage.Value.Equals("category"))
    {
        cbTreeViewGroup.Visible = false;
        UpdateSinopticCategoryManager(TreeView1.SelectedNode); //this is the functions which loads controls from database..
    }
    else if (hfPageManage.Value.Equals("device"))
    {
        cbTreeViewGroup.Visible = true;
    }
    else
    {
        cbTreeViewGroup.Visible = false;
    }
    if (!Page.IsPostBack)
    {
        LoadFunctions(); // loads some values from database into datatables
    }
    else
    {
    }
}

这是创建控制的功能

private void UpdateSinopticCategoryManager(TreeNode node = null)
{
    if (node == null)
        return;
    DataTable categoriiDT = null;
    using (var connection = new SqlConnection(Database.ConnectionString))
    {
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "SELECT * FROM categories WHERE CategoryID = @CategoryID";
            command.Parameters.Add("CategoryID", node.Value);
            SqlDataAdapter ad = new SqlDataAdapter(command);
            DataSet ds = new DataSet("CATEGORYPROPERTIES");
            connection.Open();
            ad.Fill(ds);
            // verificam sa avem date 
            if (ds.Tables.Count <= 0)
                return;
            if (ds.Tables[0].Rows.Count <= 0)
                return;
            categoriiDT = ds.Tables[0];
        }
    }
    // generate table
    Table table = new Table();
    table.Style.Add("position", "relative");
    table.Style.Add("top", "20px");
    table.Style.Add("margin-left", "20px");
    table.BorderStyle = BorderStyle.Solid;
    table.BorderWidth = 1;
    // header
    TableHeaderRow hr = new TableHeaderRow();
    for (int i = 0; i < 2; i++)
    {
        TableHeaderCell hc = new TableHeaderCell();
        if (i > 0)
        {
            hc.Text = "FUNCTION";
            //hc.Width = 200;
        }
        else
        {
            hc.Width = 100;
        }
        hr.Cells.Add(hc);
    }
    table.Rows.Add(hr);
    var inputs = (from a in categoriiDT.Columns.Cast<DataColumn>()
                 where a.ColumnName.ToLowerInvariant().Contains("input")
                 select a.ColumnName).ToArray();
    if (inputs.Count() <= 0)
        return;
    //rows input
    for (int i = 0; i < inputs.Count(); i++)
    {
        TableRow tableRow = new TableRow();
        for (int j = 0; j < 2; j++)
        {
            TableCell cell = new TableCell();
            if (j > 0)
            {
                // adaugare 2 dropdownlist
                DropDownList categList = new DropDownList();
                categList.SelectedIndexChanged += new EventHandler(categList_SelectedIndexChanged);
                foreach (DataRow row in functionsCategories.Rows)
                {
                    categList.Items.Add(new ListItem(row["FunctionCategoryName"].ToString(), row["FunctionCategoryID"].ToString()));
                }
                DropDownList funcList = new DropDownList();
                int selF = 0, selC = 0;
                for (int fi = 0; fi < functions.Rows.Count; fi++)// (DataRow row in functions.Rows)
                {
                    funcList.Items.Add(new ListItem(functions.Rows[fi]["FunctionName"].ToString(), functions.Rows[fi]["FunctionID"].ToString()));
                    if (functions.Rows[fi]["FunctionID"].ToString() == categoriiDT.Rows[0][inputs[i]].ToString())
                    {
                        selF = fi;
                        selC = Int32.Parse(functions.Rows[fi]["FunctionCategoryID"].ToString());
                    }
                }
                funcList.SelectedIndex = selF;
                categList.SelectedIndex = functionsCategories.Rows.IndexOf(
                    (from c in functionsCategories.AsEnumerable()
                    where c["FunctionCategoryID"].ToString().Equals(selC.ToString())
                    select c).FirstOrDefault());
                cell.Controls.Add(categList);
                cell.Controls.Add(funcList);
            }
            else
            {
                Label label = new Label();
                label.Text = "INPUT " + i.ToString();
                label.Style.Add("font-weight", "bold");
                cell.Controls.Add(label);
            }
            tableRow.Cells.Add(cell);
        }
        table.Rows.Add(tableRow);
    }
    //rows output
    for (int i = 0; i < 4; i++)
    {
        TableRow row = new TableRow();
        for (int j = 0; j < 2; j++)
        {
            TableCell cell = new TableCell();
            if (j > 0)
            {
                DropDownList list = new DropDownList();
                list.Width = 200;
                list.Items.AddRange(GetOutputFunctions());
                list.BorderColor = Color.Goldenrod;
                cell.Controls.Add(list);
            }
            else
            {
                Label label = new Label();
                label.Text = "OUTPUT " + i.ToString();
                label.Style.Add("font-weight", "bold");
                cell.Controls.Add(label);
             }
             row.Cells.Add(cell);
         }
         table.Rows.Add(row);
    }
    // add table to panel
    panelContent.Controls.Add(table);
}

关于这个:DropDownList categList = new DropDownList();

在Page_Load()中动态创建的控件

这可能会在代码评审中得到更快、更有效的回答https://codereview.stackexchange.com/