簡體   English   中英

在Page_Load()中動態創建的控件

[英]Dynamically created controls in Page_Load()

我有一個關於在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();

可以在codereview https://codereview.stackexchange.com/中更快,更有效地得到回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM