Reputation: 29004
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
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
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
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