1
\$\begingroup\$

I am using the OnRowDataBound() event to change the Row.BackColor based on the text. Now my issue is, this is extremely slow. I have roughly 100 rows in the ASP:Gridview and only need to evaluate the first row or index[0]. What optimization techniques do you guru's have on how to speed this process up?

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TableCell cell = e.Row.Cells[1];
        string question = cell.Text;

        if (question == "View below to get data:" | question == "Check the state information below:" | question == "Check the state information below:")
        {
            e.Row.BackColor = System.Drawing.Color.Gray;
        }
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Do you have to use c# for this? It would probably be worth using css/javascript. \$\endgroup\$
    – Sean T
    Commented Jan 4, 2018 at 21:38
  • \$\begingroup\$ @SeanT - no, either of those are viable solutions. I am just not adapt enough to do such in css/js \$\endgroup\$ Commented Jan 4, 2018 at 23:09
  • \$\begingroup\$ If it's always the first row, you can use DataBound event instead of RowDataBound. DataBound will fire only once - once all rows are bound. I'll post an example shortly. \$\endgroup\$
    – Sean T
    Commented Jan 5, 2018 at 14:35

1 Answer 1

1
\$\begingroup\$

Generally, styling should be handled using client side methods such as using css/javascript so I would recommend you do some brushing up on that side. Never the less I was like you when I first started and just jumped straight into c# so here is a purely c# based solution :).

If it's only ever going to be the first row that needs to be shaded grey you can just reference that row when the binding in complete. The event you're currently subscribing to OnRowDataBound will fire for every row. There is another event that can be accessed once all rows are completed called OnDataBound.

First thing to do would be to register this event in the html markup of your gridview, using the same approach you used to register the OnRowDataBound event.

<asp:gridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnDataBound="GridView1_OnDataBound"></asp:gridView>

Then you can code up the event in your c#.

protected void GridView1_OnDataBound(object sender, EventArgs e)
{
    if(GridView1.Rows.Count > 0) //Check there are rows bound
    {
        var Row = GridView1.Rows[0];// Get The First Row - you may have a header row. If this is the case change 0's to 1's!

        Row.BackColor = System.Drawing.Color.Gray;// Assign the back color
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.