开发者

When does code in .aspx code executed

I am trying to find out which event i should put my code that would normally be placed in .aspx. To be precise: Normally i can write something like

<asp:DropDownList ID="lst1" runat="server">
    <asp:ListItem>5</asp:ListItem>
    <asp:ListItem>6</asp:ListItem>
    <asp:ListItem>7</asp:ListItem>
    <asp:ListItem>8</asp:ListItem>
    <asp:ListItem>9</asp:ListItem>
</asp:DropDownList>

to populate my dr开发者_C百科opdownlist.

But i want this list to populate in my code behind class. I am trying to figure out which event like "On_Init", "On_Prerender" is best place to put the code so that it has same effect as above.

I am trying to use following code in my code behind class:

   for int i=5; i<=9; i++
    {
       lst1.items.add(i) 
    }

Thanks CSS


You can put it in either Page_Load or Page_Init or even Page_PreRender.

Note: if you add it to Load or PreRender, you'll want to wrap it inside a check for a postback (as necessary) so that you don't add items to the control that are already there.

if (!IsPostBack)
{
    for (int i = 5; i <= 9; i++)
         lst1.Items.Add(i.ToString());
}


I think the best place is on Page_Load method! But it depends most from your application architecture!


Page_Load is where you want to put this.

Your code has bad syntax:

protected void Page_Load(object sender, EventArgs e)
{
    for(int i = 5; i <= 9; i++)
    {
        lst1.Items.Add(i.ToString());
    }
}


If you are adding controls to a page then place it in Page_Load

If you are populating an already existing asp:DropDownList then populate the control in lst1_Load

don't use Page_Load as a catch-all

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜