开发者

Question about programmatically generated controls:"?

开发者 https://www.devze.com 2023-03-14 07:22 出处:网络
public partial class Default2 : System.Web.UI.Page { Dictionary<int, Button> btnsDic = new Dictionary<int, Button>();
public partial class Default2 : System.Web.UI.Page
{
    Dictionary<int, Button> btnsDic = new Dictionary<int, Button>();
    protected void开发者_如何学JAVA 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);
            }
        }

    }
}

Why if I make my placeholder programmatically, rather than use the placeholder that exists on my webform in a form of tags..nothing appears on the page after a postback?


You are calling PlaceHolder p = new PlaceHolder() in a loop. This means that if it did work, only the second button would be in the placeholder. Also, you need to add your new placeholder on the page. So you need to add it a control already placed on the page.

    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); 
        }
    }


Okay, I think you might be referencing your placeholder incorrectly. You are referencing it like so :-

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

But maybe you should try it like this rather :-

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

Check out this link on MSDN for more information http://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号