关于以编程方式生成的控件的问题:“?

时间:2011-06-20 12:38:20

标签: c# asp.net postback

public partial class Default2 : System.Web.UI.Page
{
    Dictionary<int, Button> btnsDic = new Dictionary<int, Button>();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            for (int i = 0; i < 2; i++)
            {
                Button newBtn = new Button();
                newBtn.CommandName = i.ToString();
                newBtn.Text = i.ToString();
                newBtn.Command += Clicked;
                btnsDic.Add(i, newBtn);
                PlaceHolder p = new PlaceHolder();
                PlaceHolder1.Controls.Add(newBtn);
                //   p.Controls.Add(newBtn); 

            }
        }
        else
        {
            Button dsa = new Button();
            dsa.Text = "This medsa";
            PlaceHolder1.Controls.Add(dsa);
        }
    }

    void Clicked(object sender, CommandEventArgs  e)
    {
        foreach (var item in btnsDic)
        {
             if (e.CommandName==item.Key.ToString())
            {
                Label lebl = new Label();
                 lebl.Text="Button number: "+e.CommandName+" was pressed";
                 this.Controls.Add(lebl);
            }
        }

    }
}

为什么我以编程方式创建占位符,而不是以标记形式使用我的webform上存在的占位符。回发后页面上没有任何内容?

2 个答案:

答案 0 :(得分:0)

你在循环中调用PlaceHolder p = new PlaceHolder()。这意味着如果它确实有效,则只有第二个按钮位于占位符中。此外,您需要在页面上添加新的占位符。所以你需要添加一个已放在页面上的控件。

    if (IsPostBack)
    {
        PlaceHolder p = new PlaceHolder();
        PlaceHolder1.Controls.Add(p);
        for (int i = 0; i < 2; i++)
        {
            Button newBtn = new Button();
            newBtn.CommandName = i.ToString();
            newBtn.Text = i.ToString();
            newBtn.Command += Clicked;
            btnsDic.Add(i, newBtn);
            p.Controls.Add(newBtn); 
        }
    }

答案 1 :(得分:-1)

好的,我认为您可能错误地引用了占位符。 你这样引用它: -

            PlaceHolder p = new PlaceHolder();
            PlaceHolder1.Controls.Add(newBtn);

但也许你应该这样尝试: -

            PlaceHolder PlaceHolder1 = new PlaceHolder();
            PlaceHolder1.Controls.Add(newBtn);

在MSDN上查看此链接以获取更多信息 http://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx