How to Bind Data in Nested GridViews Using ASP.NET C#

In this tutorial, we will delve into the advanced concept of binding data into a GridView nested within another GridView using C# coding. This technique proves valuable in scenarios where a more intricate tabular presentation of data is required. The image provided gives a visual representation of our project:

Gridview 1:

This is the primary GridView control, conventionally implemented through the toolbox in web development.

Gridview 2:

Contrary to the traditional approach, Gridview 2 isn't an actual GridView control. Instead, HTML table code is employed, providing more flexibility in data presentation.

Gridview 2 HTML Code Markup Language

Let's start by examining the HTML code for Gridview 2, which should be embedded within Gridview 1:


<table class="tblchildgrid">
  <tr>
    <th class="tblchildgrid_th">Physics</th>
    <th class="tblchildgrid_th">Chemistry</th>
    <th class="tblchildgrid_th">Mathematics</th>
    <th class="tblchildgrid_th">Computer</th>
  </tr>
  <tr>
     <td class="tblchildgrid_td">
       <asp:Label ID="lblPhysics" runat="server" Text='<%# Eval("physics") %>'></asp:Label>
     </td>
     <td class="tblchildgrid_td">    
       <asp:Label ID="lblChemistry" runat="server" Text='<%# Eval("chemistry") %>'></asp:Label>
     </td>
     <td class="tblchildgrid_td">
        <asp:Label ID="lblMaths" runat="server" Text='<%# Eval("maths") %>'></asp:Label>
     </td>
     <td class="tblchildgrid_td">
        <asp:Label ID="lblComputer" runat="server" Text='<%# Eval("computer") %>'></asp:Label>
     </td>
   </tr>
</table>

Create Database Table : StudentMarks

For demonstration purposes, we utilize the "StudentMarks" table with predefined data. The SQL script for table creation and data insertion is as follows:


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')

Gridview 1 HTML Code Markup Language

Now, integrate the HTML code for Gridview 2 into Gridview 1:


    <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='<%# Evalundefined"studentID") %>'></asp:Label>
          </ItemTemplate>
          </asp:TemplateField>
         <asp:TemplateField>
          <HeaderTemplate>
           Student Name
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblStudentName" runat="server" Text='<%# Evalundefined"studentName") %>'></asp:Label>
          </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
          <HeaderTemplate>
           Subjects
          </HeaderTemplate>
          <ItemTemplate>
           
          </ItemTemplate>
          </asp:TemplateField>
         
           <!-- Copy and Paste Gridview 2 Code Here -->
         
         <asp:TemplateField>
          <HeaderTemplate>
           Result
          </HeaderTemplate>
          <ItemTemplate>
           <asp:Label ID="lblResult" runat="server" Text='<%# Evalundefined"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

In the code-behind file (Default.aspx.cs), add the necessary namespaces:


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

C# Coding : BindGridview

BindGridview is a private method which is used to bind StudentMarks data into gridview control.


 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

How do you use a RowDataBound event in a GridView to highlight the row’s text color in ASP.NET? This example is helpful in situations where you need to highlight the GridView rows based on a specific condition, e.g., if student’s “result” is “fail”, change the text color 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");
            }
        }
    }

Conclusion

In conclusion, this tutorial has provided a comprehensive guide on implementing nested GridViews using C# coding. This approach significantly enhances the visual representation of data in web development projects, offering a more intricate and organized tabular format. Feel free to customize and expand upon this foundation to suit the specific requirements of your projects.

Post a Comment

0 Comments