TTT
TTT

Reputation: 29004

Best Practice: DataBound with loop vs RowDataBound

If you want to perform an operation on every row of a GridView, you typically would use RowDataBound. But alternatively you could also use DataBound and loop through every row there. Other than saving the foreach line of code in RowDataBound, is there any advantage/disadvantage of either method? (Performance or otherwise?)

Upvotes: 3

Views: 3491

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460208

RowDataBound is triggered for every row anyway so you don't need an additional loop in the DataBound event. However, since that is micro-optimization the main difference is that looping the rows with foreach will give you just rows with DataControlRowType DataRow whereas the RowDataBound event gives you also other RowTypes as

  • DataRow: A data row of a data control. Only DataRow rows can be data-bound.
  • EmptyDataRow: The empty row of a data-bound control. The empty row is displayed when the data-bound control has no records to display and the EmptyDataTemplate template is not null.
  • Footer: A footer row of a data control. Footer rows cannot be data-bound.
  • Header: A header row of a data control. Header rows cannot be data-bound.
  • Pager: A row that displays pager buttons or a pager control.
  • Separator

So for example, if you want the footer:

void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{  
    if(e.Row.RowType == DataControlRowType.Footer)
    {
        // ...
    }
}

With a foreach you get only DataRows:

foreach(GridViewRow row in gridView1.Rows)
{
    // no footer here
}

One advantage of the DataBound event is that you know that all rows are already databound at this stage. In RowDataBound you cannot access the controls/text of the second row in the first row. However, if you need this it is probably better to use the underlying DataSource(for example a DataTable) instead to get the required values(f.e. to aggregate columns).

So the main purpose of DataBound is if you want to trigger something just once right after the grid was databound, not for every GridViewRow. Maybe something that is not related to the GridView at all.

Upvotes: 5

James Johnson
James Johnson

Reputation: 46067

I would say that using RowDataBound holds a distinct advantage for one simple reason: it is going to get executed anyway during databinding. Looping through after the grid is databound adds an unnecessary step.

Upvotes: 2

Related Questions