在Page_Load()中动态创建控件

时间:2015-11-18 14:57:00

标签: c# asp.net events runtime controls

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

我的项目有一个母版页,我有一个1秒的定时器来更新时钟。这个计时器事件调用我的admin.aspx Page_Load()函数,所以我的方法创建了每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();

1 个答案:

答案 0 :(得分:0)

在codereview https://codereview.stackexchange.com/

中,可以更快速有效地回答这个问题