tags:

views:

147

answers:

3

What are the advantages/disadvantages of using this model

<asp:GridView Id="grdEmployees" runat="server" DataSourceID="objEmployees">
    ...
</asp:GridView>

in comparison with programmatically creating controls and binding data to them, etc...?

In which cases should one use each method?

A: 

UI state should only be affected the business process it's representing. You should therefore aspire to have your UI automatically update to changes in the business model. If you're programming the UI manually then you're more likely to have cases where the state of the business model is not accurately reflected. Programming the UI declaratively removes most of this concern. Where possible, use the declarative method.

xanadont
+1  A: 

There's no right or wrong here - it depends on what you're trying to achieve.

You can safely use static controls when you know your layout is not subject to change (i.e. a grid with a fixed number of columns), or any future possible changes are likely to be of static nature (a new column in your grid). This approach is perfectly fine and obviously faster in the average real world case.

If you need flexibility then you need to generate the controls programmatically (i.e. you need to generate a variable number of grids - or any other controls). For flexibility we mean that your layout needs to take into account variable values you won't be able to know till runtime.

JohnIdol
+1  A: 

I find uses for both models, but tend to try to use the markup in the aspx pages where I can because it is easier to read and helps me separate my view code from my logic code. The places where I programatically create controls and bind data to them are when I need a dynamic number of controls. A good example might be when you are generating a set of drop-downs dynamically for user search criteria -- I would do something like this:

SqlDataReader dr;

// Set up database connection and set dr to search query.

while(dr.Read())
{
    Literal name = new Literal();
    name.Text = dr["Name"] + ": ";

    Page.Controls.Add(name);

    DropDownList ddl = new DropDownList();
    ddl.ID = "Search_" + dr["ID"];

    SqlDataReader dr2;

    // Set up database connection and set dr2 to search items query.

    while(dr2.Read())
    {
        ListItem li = new ListItem(dr2["Name"], dr2["Value"]);
        ddl.Item.Add(li);
    }

    Page.Controls.Add(ddl);
}

One other thing to keep in mind is you can create markup controls in your aspx page and then bind them to custom DataSets that you populate in your code-behind.

Austin