Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Design time and runtime formatting of gridview - Part 10

Suggested Videos 
Part 7 - Formatting asp.net gridview control
Part 8 - Formatting gridview using rowdatabound event
Part 9 - Formatting gridview based on row data



GridView control provides several inbuilt styles to format different sections of the gridview. The following are some of the style properties and the sections they can format.
ControlStyle - Use to apply the formatting on the entire gridview control
RowStyle - Use to format all rows in the gridview
AlternatingRowStyle - Use to format all alternating rows in the gridview
HeaderStyle - Use to format the header of the gridview control
FooterStyle - Use to format the footer of the gridview control
EditRowStyle - Use to format when the row is in edit mode.



By default, the footer of the girdview control is not visible. To show the footer, set "ShowFooter" property of the gridview control to true.

If you are not very good at designing, then you may use "AutoFormat" feature of the gridview control.

These styles can be applied declaratively at design time or dynamically at runtime based on the underlying data. At design time, the styles can be applied using properties window or directly in the HTML source.

Now, let us understand changing the styles dynamically based on underlying data. I have tblEmployee table, as shown below. 


I want to display this data in a gridview control. All the employee rows, with salary greater than 70,000 should have a "RED" background color and white font colour. Obviously this cannot be done at design time. At runtime, we need to check the value in "AnnualSalary" column for each row, and if it is greater than 70,000, then we need to set the "BackColor" property of that row to "Red". This can be very easily achieved using RowDataBound event. The output should be as shown below.


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // Loop thru each datarow in the gridview
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // You can also retrieve salary using cell index in the row
        // Avoid using index, as this may not work correctly if the
        // order of columns is changed in the gridview control
        // int salary = Convert.ToInt32(e.Row.Cells[2].Text);
        // Retrieve salary
        int salary = Convert.ToInt32
            (DataBinder.Eval(e.Row.DataItem, "AnnualSalary"));
        // If Salary > 70000, set your styles
        if (salary > 70000)
        {
            e.Row.BackColor = System.Drawing.Color.Red;
            e.Row.ForeColor = System.Drawing.Color.White;
        }
    }
}

No comments:

Post a Comment

It would be great if you can help share these free resources