Asp.net Tutorial: Changing Gridview Row Color and Text

Introduction

In this tutorial, we'll explore how to bind data from a database table, specifically the 'StudentMarks' table, to a GridView control in an ASP.NET web application. We will also implement a feature that dynamically changes the text color of rows where the student result is marked as "Fail." This tutorial will guide you through the process, step by step, covering database setup, HTML markup, C# coding, and even provide a demonstration video.

Create Database Table : StudentMarks

The first step involves creating a database table named 'StudentMarks.' This table contains information such as student ID, name, marks in various subjects, and the result. The predefined data is inserted using SQL scripts within the tutorial. This table will be used to demonstrate data binding to the GridView control.


CREATE TABLE StudentMarks(
studentID int,
studentName varchar(30),
physics int,
chemistry int,
maths int,
computer int,
result varchar(5))
insert into StudentMarks values(1,'Krishna', 35,35,35,35,'Pass')
insert into StudentMarks values(2,'Parmesh', 75,56,46,71,'Pass')
insert into StudentMarks values(3,'Sathya', 64,83,25,63,'Fail')
insert into StudentMarks values(4,'Naresh', 37,51,42,67,'Pass')
insert into StudentMarks values(4,'Naresh', 43,31,62,17,'Fail')

HTML MarkUp Language

In the 'Default.aspx' design page, we use the GridView control to display the data. The HTML markup includes code for columns such as StudentID, Student Name, Physics, Chemistry, Maths, Computer, and Result. The design ensures an organized and visually appealing representation of the data.


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            CellPadding="4" ForeColor="#333333" GridLines="None" 
            onrowdatabound="GridView1_RowDataBound">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
         <asp:TemplateField>
          <HeaderTemplate>
           StudentID
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblStudentID" runat="server" Text='<%# Eval("studentID") %>'></asp:Label>
          </ItemTemplate>
          </asp:TemplateField>
         <asp:TemplateField>
          <HeaderTemplate>
           Student Name
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblStudentName" runat="server" Text='<%# Eval("studentName") %>'></asp:Label>
          </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
          <HeaderTemplate>
           Physics
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblPhysics" runat="server" Text='<%# Eval("physics") %>'></asp:Label>
          </ItemTemplate>
          </asp:TemplateField>
         <asp:TemplateField>
          <HeaderTemplate>
           Chemistry
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblChemistry" runat="server" Text='<%# Eval("chemistry") %>'></asp:Label>
          </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
          <HeaderTemplate>
           Maths
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblMaths" runat="server" Text='<%# Eval("maths") %>'></asp:Label>
          </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
          <HeaderTemplate>
           Computer
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblComputer" runat="server" Text='<%# Eval("computer") %>'></asp:Label>
          </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
          <HeaderTemplate>
           Result
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblResult" runat="server" Text='<%# Eval("result") %>'></asp:Label>
          </ItemTemplate>
         </asp:TemplateField>
        </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>

C# Coding

Add Namespace to Default.aspx.cs


using System.Data;
using System.Data.SqlClient;

C# Coding : BindGridview

The C# code in the 'Default.aspx.cs' file includes a method named 'BindGridview.' This private method uses SqlDataAdapter to fetch data from the 'StudentMarks' table and binds it to the GridView control. The method is called in the Page_Load event to ensure data binding occurs when the page is loaded for the first time.


 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
  private void BindGridview()
    {        
        SqlDataAdapter da = new SqlDataAdapter("Select * from StudentMarks", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }

C# Coding : Gridview_RowDataBound

To achieve the dynamic text color change based on the 'Result' value, we utilize the GridView_RowDataBound event. This event is triggered for each row during data binding. The C# code within this event checks if the 'Result' is marked as "Fail" and changes the text color of relevant labels to red.


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblSID = (Label)e.Row.FindControl("lblStudentID");
            Label lblSName = (Label)e.Row.FindControl("lblStudentName");
            Label lblPhyscs = (Label)e.Row.FindControl("lblPhysics");
            Label lblChemistry = (Label)e.Row.FindControl("lblChemistry");
            Label lblMaths = (Label)e.Row.FindControl("lblMaths");
            Label lblComputer = (Label)e.Row.FindControl("lblComputer");
            Label lblResult = (Label)e.Row.FindControl("lblResult");
            if (lblResult.Text == "Fail")
            {
                lblSID.Style.Add("color", "#f00");
                lblSName.Style.Add("color", "#f00");
                lblPhyscs.Style.Add("color", "#f00");
                lblChemistry.Style.Add("color", "#f00");
                lblMaths.Style.Add("color", "#f00");
                lblComputer.Style.Add("color", "#f00");
                lblResult.Style.Add("color", "#f00");
            }
        }
    }

Watch Gridview Row Text Color Change Demo Video

To provide a visual demonstration, a YouTube video is embedded in the tutorial. The video showcases the GridView in action, with rows dynamically changing text color when the student's result is marked as "Fail."


Conclusion

By following this tutorial, you have learned how to bind data from a database table to a GridView control in an ASP.NET web application. Additionally, you have implemented a feature to dynamically change the text color of rows based on specific conditions, enhancing the visual representation of student records. Feel free to apply these concepts to your own projects and customize the code to suit your needs. Happy coding!

Post a Comment

0 Comments