How to add footer and adding data in grid view control in Asp.net
Step 2 : Open that page and Drag and Drop GridView control from Toolbox Diaglog box
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
Step 3 : After adding grid view open server side code of that page. opne .cs file or .vb file
Step 4 : Create one class Student and paste below code in file
public class Student
{
public int RollNo { get; set; }
public string StudentName { get; set; }
public string Address { get; set; }
public string MobileNo { get; set; }
public int Marks { get; set; }
}
Step 5 : Create student record first and then paste below code
List<Student> data = new List<Student>();
data.Add(new Student { RollNo = 1, StudentName = "Student1", MobileNo = "1234567890", Address = "India", Marks = 50 });
data.Add(new Student { RollNo = 2, StudentName = "Student2", MobileNo = "1234567890", Address = "Uk", Marks = 70 });
//doing sub total of marks and adding to ViewState
int totalMarks = 0;
foreach (Student item in data)
{
totalMarks += item.Marks;
}
ViewState["TotalAmount"] = totalMarks.ToString();
GridView1.DataSource = data;
GridView1.DataBind();
Step 6 : After adding record and making sub total of marks then add below code of grid view control and remember set ShowFooter property to true.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
ShowFooter="True" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="RollNo" HeaderText="Roll No" />
<asp:BoundField DataField="StudentName" HeaderText="Studnet Name" SortExpression="StudentName" />
<asp:BoundField DataField="MobileNo" HeaderText="Mobile No" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:TemplateField HeaderText="Address">
<FooterTemplate>
<b> Total Marks :</b>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Address") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Marks">
<FooterTemplate>
<b><asp:Label ID="lblMarksTotal" runat="server" ></asp:Label> <b>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Marks") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Step 7 : Also add onRowDatabound event of grid view and paste below code in code behind.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
((Label)e.Row.FindControl("lblMarksTotal")).Text = ViewState["TotalAmount"].ToString();
}
}
Step 8 : Check your project is they showing perfect sub total or not.
No comments:
Post a Comment
Thank you for your interest .