Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I Want To Display Last Column Of Grid View In Color Format.
I.e I want to apply Css on Last Column Of gridview

I Have Created Stored Procedure To Bind Data With Gridview
Its Working Fine

What I have tried:

I Have Created Css Class As

<style>
        .highlighted 
  {
     color:Red ! important;
     background-color: blue ! important;
  }
    </style>
</head>



then On PreRender Event Of Gridview Control I have wriiten Code as


protected void GridView1_PreRender1(object sender, EventArgs e)
        {

            try
            {
                GridViewRow getRow = GridView1.Rows[GridView1.Rows.Count - 1];
                getRow.Attributes.Add("class", "highlighted");
            }
            catch(Exception ex)
            {
                Response.Write(ex);
            }
}


It Showing Exception in Gridview1_prerender as

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: in
Posted
Updated 15-Jul-17 2:33am

1 solution

From where I see this, the problem is with the hardcoded [...Count - 1] thing, why do that in the first place, and leave it exposed to several conditions? For example, what will happen if the Count property is zero (the list is empty?). Instead of this, I would personally try using this,
C#
GridViewRow row = null;
if(GridView1.Rows.Count == 0) {
   // Handle the empty grid
} else if (GridView1.Rows.Count == 1) {
   row = GridView1.Rows[0]; // Capture this row, or ignore the single row.
} else if (GridView1.Rows.Count > 1) {
   row = GridView1.Rows[GridView1.Rows.Count - 1];
}

if(row != null) {
   // Check if there is a row
   row.Attributes.Add("class", "highlighted");
}

This should properly ensure that your problems are targeted and there is a solution, that the code can take to prevent code crashes.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900