Wednesday, February 15, 2012

In this example i am going to demonstrate how to display running total in footer row or footer template of GridView in ASP.NET using C# and VB.NET. This method works with paging enabled gridview as well.



For demo purpose gridview is populated using sqldatasource having table with columns ID ,Name,Amount

I m showing total of amount column is gridview footer. for this we need to sum the the column in RowDataBound Even of Gridiew













Html source of gridview is
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False"
              DataKeyNames="ID" DataSourceID="SqlDataSource1" 
              OnRowDataBound="GridView1_RowDataBound" 
              ShowFooter="True" AllowPaging="True" PageSize="5" 
              BackColor="#ffffff" BorderColor="AliceBlue" 
              BorderStyle="None" BorderWidth="1px" 
              CellPadding="3" 
              CellSpacing="2" FooterStyle-BackColor="#da821e" 
              FooterStyle-ForeColor="#ffffff" 
              RowStyle-BackColor="#003366" 
              RowStyle-ForeColor="#ffffff" 
              AlternatingRowStyle-BackColor="#da821e">
<Columns>
     <asp:BoundField DataField="ID" HeaderText="ID" 
                     InsertVisible="False" ReadOnly="True"
                     SortExpression="ID" />
     <asp:BoundField DataField="Name" HeaderText="Name" 
                     InsertVisible="False" ReadOnly="True"
                     SortExpression="Name" FooterText="Total"/>
     <asp:TemplateField HeaderText="Amount">
     <ItemTemplate>
     <asp:Label ID="lblAmount" runat="server" 
                Text='<%# "$"+Eval("Amount").ToString()%>'>
     </asp:Label>
     </ItemTemplate>
     <FooterTemplate>
     <asp:Label ID="lblTotal" runat="server"></asp:Label>
     </FooterTemplate>
     </asp:TemplateField>
     </Columns>
     <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
     <HeaderStyle BackColor="#da821e" Font-Bold="True" 
                  ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Amount] FROM [Expenses]">
</asp:SqlDataSource>
Now we need to write code for summing the column in RowdataBound Even of GridView

C# code behind
01public partial class _Default : System.Web.UI.Page
02{
03    decimal grdTotal = 0;
04    protected void Page_Load(object sender, EventArgs e)
05    {
06 
07    }
08protected void GridView1_RowDataBound
09                   (object sender, GridViewRowEventArgs e)
10{
11 if (e.Row.RowType == DataControlRowType.DataRow)
12 {
13  decimal rowTotal = Convert.ToDecimal
14              (DataBinder.Eval(e.Row.DataItem, "Amount"));
15  grdTotal = grdTotal + rowTotal;
16 }
17 if (e.Row.RowType == DataControlRowType.Footer)
18 {
19  Label lbl = (Label)e.Row.FindControl("lblTotal");
20  lbl.Text = grdTotal.ToString("c");
21 }
22}
23}

VB.NET code behind
01Public Partial Class _Default
02    Inherits System.Web.UI.Page
03    Private grdTotal As Decimal = 0
04    Protected Sub Page_Load
05    (ByVal sender As Object, ByVal e As EventArgs)
06 
07End Sub
08 
09Protected Sub GridView1_RowDataBound
10(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
11 
12If e.Row.RowType = DataControlRowType.DataRow Then
13Dim rowTotal As Decimal =
14Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"))
15grdTotal = grdTotal + rowTotal
16End If
17 
18If e.Row.RowType = DataControlRowType.Footer Then
19Dim lbl As Label = DirectCast(e.Row.FindControl
20                           ("lblTotal"), Label)
21lbl.Text = grdTotal.ToString("c")
22End If
23End Sub
24End Class

Hope this helps
In this example i am going to describe how to create SubReports in Crystal Reports or Crystal Reports SubReport in ASP.NET.

For this i have used two tables from MS SQL database named Employees and Projects.
Main Crystal Report is fetching data from both the tables and is grouped by Project Name

SubReport is used to display information about respective project and fetching data from Projects Table.

Schema for both the tables in shown below in images, create tables accordingly and add relevant data in it to start.


You can click on Images to Enlarge 

 
  
To start , Create a new website in VS and right click on Solution Explorer and select Add new Item > Crystal Report. In the wizard window choose Using the Report Wizard radio button and Standard type in Choose an Expert section.

 
In next screen select Expand OLEDB(ADO) and Choose create new connection 

 
Select Microsoft OLEDB Provider for SQL server and click next 

 
In next screen check the Integrated security checkbox so that report doesn't ask for username and password  Enter you SQL Server name and Select DataBase from the dropdown ,

 
In next window expand and locate your tables you want to use and add them in right pane 

 
  
In next screen select the fields you want to display in main report and add them in right pane , in my case i am showing fields from two tables in main report 
 Now select the field which you want report to be grouped by ( in this example i m grouping report by Project Name)

Select the report style you want and finish the wizard 

 Now to add a subReport Right click in group header section (below Group #1 Name) 
Choose Insert > SubReport , Place the ractangle where you want SubReport to be displayed. a wizard window will open prompltly

 
Enter report Name and click on report wizard buttonin next screen ,
  
  
  
Choose the table and fields you want to use in SubReport in next two screens and click on finish 
Now Insert subReport window will open again , In this window click on Link Tab and select the field on which you want to filter SubReport or the ID of the record to show SubReport. I am using ProjectID in this example.

This is how design of report will look like 

 
And this is how report preview will look

 
Save , build and rum the website. 
Now if you don't want to show SubReport but want to put a hyperlink instead or want to create On-Demand SubReport then do these changes in the design of report 
Right click on SubReport in Design View and select Format Object 

 
In the window opened ,Go to SubReport tab, Change the SubReport name to text you want to show as hyperlink, Check the On-demand SubReport check box and click on ok 
 
 
Now design of report will look like image below 

 

On default.aspx page drag CrystalReportViewer from toolbox and assign CrystalReport we just created as source
Html source will go like this (AutoGenerated)
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" 
                        AutoDataBind="True" Height="1039px" 
                        ReportSourceID="CrystalReportSource1" 
                        Width="901px" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>

Save, build and run the solution , this is how report will look like 

Hope this helps
CheckAll CheckBox In GridView to Edit and Update

Check All Checkbox In GridView To Bulk Edit Or Update in ASP.NET with C# and VB.NET.
In this example i am going to describe how to implement CheckAll CheckBox in GridView to check all the rows in gridView.

For this i have put a checkBox in header Template of gridview which on checking will check all the rows in gridview using server side code.



Html Source of gridView
<asp:GridView ID="GridView1" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="false" 
              CellPadding="2" ForeColor="#333333" 
              GridLines="Both" 
              DataKeyNames="ID" 
              OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" 
              AutoPostBack="true" 
              OnCheckedChanged="chkSelectAll_CheckedChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" 
              AutoPostBack="true" 
              OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="ID" 
                SortExpression="ID"/>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" 
             Text='<%# Bind("Name") %>' ForeColor="Blue" 
             BorderStyle="none" BorderWidth="0px" 
             ReadOnly="true" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server" 
             Text='<%# Bind("Location") %>' 
             ForeColor="Blue" BorderStyle="none" 
             ReadOnly="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]" 
DeleteCommand="DELETE FROM Details WHERE (ID = @ID)" 
UpdateCommand="UPDATE [Details] SET [Name] = @Name, 
               [Location] = @Location WHERE [ID] = @ID">
<DeleteParameters>
<asp:Parameter Name="ID" />
</DeleteParameters>

<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="Location" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>

<asp:Button ID="btnUpdate" runat="server" 
            OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server" 
            OnClick="btnDelete_Click" 
            Text="Delete" />

C# Code behind
01protected void chkSelectAll_CheckedChanged
02                               (object sender, EventArgs e)
03{
04 CheckBox chkAll =
05    (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
06 if (chkAll.Checked == true)
07 {
08   foreach (GridViewRow gvRow in GridView1.Rows)
09   {
10    CheckBox chkSel =
11         (CheckBox)gvRow.FindControl("chkSelect");
12    chkSel.Checked = true;
13    TextBox txtname = (TextBox)gvRow.FindControl("txtName");
14    TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
15    txtname.ReadOnly = false;
16    txtlocation.ReadOnly = false;
17    txtname.ForeColor = System.Drawing.Color.Black;
18    txtlocation.ForeColor = System.Drawing.Color.Black;
19   }
20 }
21 else
22 {
23  foreach (GridViewRow gvRow in GridView1.Rows)
24  {
25   CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
26   chkSel.Checked = false;
27   TextBox txtname = (TextBox)gvRow.FindControl("txtName");
28   TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
29   txtname.ReadOnly = true;
30   txtlocation.ReadOnly = true;
31   txtname.ForeColor = System.Drawing.Color.Blue;
32   txtlocation.ForeColor = System.Drawing.Color.Blue;
33   }
34  }
35}

VB.NET code behind
01Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
02    Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"), CheckBox)
03    If chkAll.Checked = True Then
04        For Each gvRow As GridViewRow In GridView1.Rows
05            Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
06            chkSel.Checked = True
07            Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
08            Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
09            txtname.[ReadOnly] = False
10            txtlocation.[ReadOnly] = False
11            txtname.ForeColor = System.Drawing.Color.Black
12            txtlocation.ForeColor = System.Drawing.Color.Black
13        Next
14    Else
15        For Each gvRow As GridViewRow In GridView1.Rows
16            Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
17            chkSel.Checked = False
18            Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
19            Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
20            txtname.[ReadOnly] = True
21            txtlocation.[ReadOnly] = True
22            txtname.ForeColor = System.Drawing.Color.Blue
23            txtlocation.ForeColor = System.Drawing.Color.Blue
24        Next
25    End If
26End Sub


Hope this helps
In this example i am going to describe Cross Page Posting or postback in ASP.NET 2.0 / 3.5 using C# and VB.NET.

Cross Page posting or cross page postback is used to submit a form on one page (say default.aspx) and retrieve values of controls of this page on another page (say Default2.aspx)

There are two ways we can use cross page postsbacks in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true"  
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
First Name:
<asp:TextBox ID="txtFirstName" runat="server">
</asp:TextBox><br /><br />
Last Name:
<asp:TextBox ID="txtLastName" runat="server">
</asp:TextBox><br /><br /><br />
        
<asp:Button ID="btnSubmit" runat="server" 
            OnClick="btnSubmit_Click" 
            PostBackUrl="~/Default2.aspx"
            Text="Submit to Second Page" /><br />
</div>
</form>
</body>
</html>
Don't forget to set PostBackUrl Property of Button
PostBackUrl="~/Default2.aspx"

Now to retrieve values of textBoxes on Default2.aspx page, write below mentioned code in Page_Load event of second page (Default2.aspx)
C# code behind
01protected void Page_Load(object sender, EventArgs e)
02{
03    //Check whether previous page is cross page post back or not
04    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
05    {
06        TextBox txtPbFirstName = (TextBox)PreviousPage.FindControl("txtFirstName");
07        TextBox txtPbLastName = (TextBox)PreviousPage.FindControl("txtLastName");
08        Label1.Text = "Welcome " + txtPbFirstName.Text + " " + txtPbLastName.Text;
09    }
10    else
11    {
12        Response.Redirect("Default.aspx");
13    }
14}
VB.NET Code behind
01Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
02    'Check whether previous page is cross page post back or not
03    If PreviousPage IsNot Nothing AndAlso PreviousPage.IsCrossPagePostBack Then
04        Dim txtPbFirstName As TextBox = DirectCast(PreviousPage.FindControl("txtFirstName"), TextBox)
05        Dim txtPbLastName As TextBox = DirectCast(PreviousPage.FindControl("txtLastName"), TextBox)
06        Label1.Text = ("Welcome " & txtPbFirstName.Text & " ") + txtPbLastName.Text
07    Else
08        Response.Redirect("Default.aspx")
09    End If
10End Sub

If you are using masterpages then you need to write code to FindControl as mentioned below
1ContentPlaceHolder exampleHolder =(ContentPlaceHolder)Page.PreviousPage.Form.FindControl ("Content1"));
2TextBox txtExample = exampleHolder.FindControl("txtFirstName");

2nd Method
Using Property to expose and Consume values of TextBox
If we are using this method then we don't need to use FindControl method at all
For this we need to create property in code behind of the page to be cross page post back (Default.aspx)
Html of the page needs no changes ,
C# code behind for Default.aspx
01public TextBox pbTxtFirstName
02    {
03        get
04        {
05            return txtFirstName;
06        }
07    }
08 
09    public TextBox pbTxtLastName
10    {
11        get
12        {
13            return txtLastName;
14        }
15    }

VB.NET
01Public ReadOnly Property pbTxtFirstName() As TextBox
02    Get
03        Return txtFirstName
04    End Get
05End Property
06 
07Public ReadOnly Property pbTxtLastName() As TextBox
08    Get
09        Return txtLastName
10    End Get
11End Property
Now to retrieve or consume exposed properties on Second page we need to add below mentioned page directive in html source of Default2.aspx page(usually at the top of page)
<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
Now write this code in page_Load event of second page to retrieve values of controls
C# code
01protected void Page_Load(object sender, EventArgs e)
02{
03    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
04    {
05        Label1.Text = "Welcome " + PreviousPage.pbTxtFirstName.Text + " " + PreviousPage.pbTxtLastName.Text;
06    }
07    else
08    {
09        Response.Redirect("Default.aspx");
10    }
11}
VB Code
1Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
2    If PreviousPage IsNot Nothing AndAlso PreviousPage.IsCrossPagePostBack Then
3        Label1.Text = ("Welcome " & PreviousPage.pbTxtFirstName.Text & " ") + PreviousPage.pbTxtLastName.Text
4    Else
5        Response.Redirect("Default.aspx")
6 
7    End If
8End Sub

Hope this helps