25

Merge GridView Cells Or Columns In Row ASP.NET C# VB.NET

In this example i am going to describe how to Merge GridView Cells Or Columns In Gridview Rows Using C# and VB.NET in ASP.NET Containing Same Data or content. For this i m using DataBound Event of gridview, counting total rows and then checking each cells value against value of same cell in previous row and then setting the RowSpan of cells.

Merge GridView Cells Or Columns

For this i have created a table containing Counties ,states and respective cities and country and state cells / columns are merged in rows having same country or states.


For knowing how to merge Gridview headers read article below
Merging GridView Header Columns or multiple Headers


You would also like to read
Hide GridView Columns In Normal Mode and Visible In Edit


Running Total In Gridview Footer in ASP.NET C# VB.NET











Html source of the page look like this
<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="False"  
    BorderStyle="None" BorderWidth="1px" CellPadding="4" 
    GridLines="Horizontal" ForeColor="Black" 
    Height="119px" DataSourceID="SqlDataSource1" 
    OnDataBound="GridView1_DataBound1"> 
            <Columns>
            <asp:BoundField DataField="Country" 
                            HeaderText="Country" 
                            SortExpression="Country" />
            <asp:BoundField DataField="State" 
                            HeaderText="State" 
                            SortExpression="State" />
            <asp:BoundField DataField="City" 
                            HeaderText="City" 
                            SortExpression="City" />
        </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Country], [State], [City] 
               FROM [Details] ORDER BY [State]">
</asp:SqlDataSource>

C# code behind
protected void GridView1_DataBound1(object sender, EventArgs e)
{
  for (int rowIndex = GridView1.Rows.Count - 2; 
                                     rowIndex >= 0; rowIndex--)
  {
    GridViewRow gvRow = GridView1.Rows[rowIndex];
    GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
    for (int cellCount = 0; cellCount < gvRow.Cells.Count; 
                                                  cellCount++)
    {
     if (gvRow.Cells[cellCount].Text == 
                            gvPreviousRow.Cells[cellCount].Text)
     {
       if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
       {
         gvRow.Cells[cellCount].RowSpan = 2;
       }
       else
       {
        gvRow.Cells[cellCount].RowSpan = 
            gvPreviousRow.Cells[cellCount].RowSpan + 1;
       }
       gvPreviousRow.Cells[cellCount].Visible = false;
    }
   }
 }
}
VB.NET code behind
Protected Sub GridView1_DataBound1
           (ByVal sender As Object, ByVal e As EventArgs)

For rowIndex As Integer = GridView1.Rows.Count - 2 To 0 Step -1
    Dim gvRow As GridViewRow = GridView1.Rows(rowIndex)
    Dim gvPreviousRow As GridViewRow = GridView1.Rows(rowIndex + 1)
    For cellCount As Integer = 0 To gvRow.Cells.Count - 1
    If gvRow.Cells(cellCount).Text = 
                         gvPreviousRow.Cells(cellCount).Text Then
    If gvPreviousRow.Cells(cellCount).RowSpan < 2 Then
    gvRow.Cells(cellCount).RowSpan = 2
    Else
    gvRow.Cells(cellCount).RowSpan = 
                       gvPreviousRow.Cells(cellCount).RowSpan + 1
    End If
    gvPreviousRow.Cells(cellCount).Visible = False
    End If
    Next
  Next
End Sub


13

SubReport In Crystal Reports

In this example i am going to describe how to Create SubReports in Crystal Reports or Crystal Reports SubReport in ASP.NET Using C# And VB.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 Crystal Report SubReport will look like


Hope this helps.

20

Combine Multiple Columns And Records In MS SQL Server

Combine Multiple Columns And Records Into Comma Separated One Column In MS SQL Server. In this example i am going to describe how to combine multiple columns and records in one column in MS SQL.

Here is the scenario

I have a table having Employees names and their respective Department names,
now i want to show Employees names separated by comma into one column and respective Department name in another column.



My table schema is shown in the image below

Combine Multiple Columns And Records Sql Server

And this is Data into table



I want output in following format

                                  Department                               FirstName
                                   IT                                             amiT,Emp1,Emp5
                                  Admin                                       Shobhit, Emp3,Emp7


and so on

To get this desired result we need to write below mentioned query

SELECT DISTINCT
Department,
EmpNames = substring( ( SELECT ', ' + FirstName 
FROM Employees e2
WHERE e2.Department = e1.Department FOR XML path(''), elements 
),2,500)
FROM Employees e1

And the output of this SQL Query would be



Hope this helps


24

Running Total In Gridview Footer In ASP.NET C# VB.NET

In this example i am going to demonstrate how to Display Running Total In GridView Footer Row In ASP.NET using C# and VB.NET. This method works with paging enabled gridview as well.

Running Total In Gridview Footer In ASP.NET

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
public partial class _Default : System.Web.UI.Page 
{
    decimal grdTotal = 0;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void GridView1_RowDataBound
                   (object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  decimal rowTotal = Convert.ToDecimal
              (DataBinder.Eval(e.Row.DataItem, "Amount"));
  grdTotal = grdTotal + rowTotal;
 }
 if (e.Row.RowType == DataControlRowType.Footer)
 {
  Label lbl = (Label)e.Row.FindControl("lblTotal");
  lbl.Text = grdTotal.ToString("c");
 }
}
}


VB.NET code behind
Public Partial Class _Default
    Inherits System.Web.UI.Page
    Private grdTotal As Decimal = 0
    Protected Sub Page_Load
    (ByVal sender As Object, ByVal e As EventArgs)
        
End Sub

Protected Sub GridView1_RowDataBound
(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowTotal As Decimal = 
Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"))
grdTotal = grdTotal + rowTotal
End If

If e.Row.RowType = DataControlRowType.Footer Then
Dim lbl As Label = DirectCast(e.Row.FindControl
                           ("lblTotal"), Label)
lbl.Text = grdTotal.ToString("c")
End If
End Sub
End Class


Hope this helps

Other gridview articles:
Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

Pouplating Multiple DetailsView based on single GridView using DataKeyNames

Merging GridView Headers to have multiple Headers in GridView

Search Records In GridView And Highlight Results Using AJAX ASP.NET

Insert update Delete record in GridView using SqlDataSource ItemTemplate and EditItemTemplate

22

Crystal Reports In Winforms Windows Forms With Parameters

In this example i am explaining how to create Crystal Reports In Winforms Or Windows Forms Application With Parameters from user to filter report using C#.NET and VB.NET

Crystal Reports In Winforms Or Windows Forms Application With Parameters
For this i have created two tables in database named Employees and Projects and fetching data from both tables

I've grouped results by Department name using group expert in crystal reports and put a dropdown on the form to select project name to display related report.

Employee table schema

ID    int  
FirstName    varchar(50)
LastName    varchar(50)   
Department    varchar(50)   
ProjectID    numeric(18, 0)  
Expenses    money   


Projects table schema 

ProjectID    numeric(18, 0)   
ProjectName    varchar(50)  









Create a new project in VS and go to solution explorer and add new item > crystal report.
Select Blank report option from the wizard window
 
Now click on CrystalReports menu and select DataBase Expert 
Now in next window expand Create new connection section and OLEDB(ADO) and in next window select SQL Native Client

Enter you SQL Server name , username and password , select database name from the dropdown and click on ok
In next window expand to find your tables and add them in right pane
Click OK to finish

Now Right Click on Group Name Fields in Field Explorer and Select Group Expert.
In group expert box select the field on which you want data to be grouped.
 
  
Design your report by dragging the fields in section3 (Details) 
my design look like this  
In the form add a combobox and drag and drop CrystalReport Viewer from toobox. click on smart tag and choose the report we created earlier (CrystalReport1.rpt) 
Form look like this 
When we build and rum this report , it asks for Database login username and password , we need to provide database username and password in code behind.
 we need to write code in code behind to filter report based on user selected value or value provided by user 
C# code behind
//Code to populate dropdown
//Fill dropdown in form_Load event by calling 
//function written below
private void FillDropDown()
{
 SqlConnection con = new SqlConnection
       (ConfigurationManager.AppSettings["myConnection"]);
 SqlCommand cmd = new SqlCommand
("Select distinct ProjectID,ProjectName from Projects", con);
 con.Open();
 DataSet objDs = new DataSet();
 SqlDataAdapter dAdapter = new SqlDataAdapter();
 dAdapter.SelectCommand = cmd;
 dAdapter.Fill(objDs);
 cmbMonth.DataSource = objDs.Tables[0];
 cmbMonth.DisplayMember = "ProjectName";
 cmbMonth.ValueMember = "ProjectID";
 cmbMonth.SelectedIndex = 0;
}
private void cmbMonth_SelectedIndexChanged
              (object sender, EventArgs e)
{
      //Create object of report 
CrystalReport1 objReport = new CrystalReport1();

    //set database login information
objReport.SetDatabaseLogon
    ("amit", "password", @"AVDHESH\SQLEXPRESS", "TestDB");

//write formula to pass parameters to report 
crystalReportViewer1.SelectionFormula 
    ="{Projects.ProjectID} =" +cmbMonth.SelectedIndex;
crystalReportViewer1.ReportSource = objReport;
}
      

VB.NET code behind
Private Sub FillDropDown()
    Dim con As New SqlConnection
   (ConfigurationManager.AppSettings("myConnection"))

    Dim cmd As New SqlCommand
("Select distinct ProjectID,ProjectName from Projects", con)
    con.Open()
    Dim objDs As New DataSet()
    Dim dAdapter As New SqlDataAdapter()
    dAdapter.SelectCommand = cmd
    dAdapter.Fill(objDs)
    cmbMonth.DataSource = objDs.Tables(0)
    cmbMonth.DisplayMember = "ProjectName"
    cmbMonth.ValueMember = "ProjectID"
    cmbMonth.SelectedIndex = 0
End Sub

Private Sub cmbMonth_SelectedIndexChanged
(ByVal sender As Object, ByVal e As EventArgs)
    
    'Create object of report 
    Dim objReport As New CrystalReport1()
    
    'set database login information
    objReport.SetDatabaseLogon
("amit", "password", "AVDHESH\SQLEXPRESS", "TestDB")
    
    'write formula to pass parameters to report 
    crystalReportViewer1.SelectionFormula 
= "{Projects.ProjectID} =" & cmbMonth.SelectedIndex

    crystalReportViewer1.ReportSource = objReport
End Sub

Hope this helps

Download sample code



other articles on Crystal reports and winforms
Creating Crystal reports in ASP.NET C# VB.NET

Creating winforms AutoComplete TextBox using C# in Windows application

OpenFileDialog in winforms windows forms C# .NET VB.NET windows application

SubReports in Crystal Reports in ASP.NET

37

Scrollable GridView With Fixed Headers Asp.Net

Scrollable GridView With Fixed Headers Using CSS Example In Asp.Net 2.0,3.5,4.0 C# VB.NET. In this example i am going to show how to create scrollable GridView with fixed headers which don't get scrolled with records and stay on the top in asp.net using css, I've tested this code on IE7 and Firefox 2.0 , 3.5.

Scrollable GridView With Fixed Headers In Asp.Net 2.0,3.5,4.0 C# VB.NET

For this we need to add css to headers of gridview to keep them on the top.

First of all place a Panel on the aspx page from toolbox. Set height to 200px and width to 200px
and scrollbars to Vertical.

Now add a gridview inside this Panel and set the datasource to populate gridview.

We can also use JQuery to create Fixed Header Scrollable GridView






HTML SOURCE
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" Height="200px" 
                       Width="200px" ScrollBars="Vertical">

<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1"
              RowStyle-VerticalAlign="Bottom"
              OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" 
                InsertVisible="False" 
                ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" 
                                 SortExpression="Name" />
<asp:BoundField DataField="Location" HeaderText="Location" 
                             SortExpression="Location" />
</Columns>
<HeaderStyle CssClass="header"Height="20px" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]">
</asp:SqlDataSource>
</asp:Panel>
</div>
</form>

Now Add below mention css style in the head section of page
<head runat="server">
<title>Creating scrollable GridView with fixed headers</title>
<style type="text/css">
  .header
  {
    font-weight:bold;
    position:absolute;
    background-color:White;
  }
  </style>
</head>

Build and run the code.

This code works fine but there is one bug in it , first record of GridView gets hidden behind the fixed column headers.

To fix this issue we need to set height of first row in gridview to double of height of header row or double the height of other rows of gridview. for this we need to add below mentioned code in RowDataBound event of GridView.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if(e.Row.RowIndex == 0)
           e.Row.Style.Add("height","40px");
        }
    }

Now the output will be as shown in image, In my example i've set the header height to "20px" using headerStyle in html source. so i'll be setting height of first row to "40px"












Download sample code attached



69

FileUpload Save Images In Database In ASP.NET

This example explains how to Save Images In Sqlserver Database In Asp.Net Using File Upload Control.
I am Uploading Images using FileUpload Control and saving or storing them in SQL Server database in ASP.NET with C# and VB.NET.

FileUpload Save Images In Database In ASP.NET

Database is having a table named Images with three columns.
1. ID Numeric Primary key with Identity Increment.
2. ImageName Varchar to store Name of picture.
3. Image column to store image in binary format.

After uploading and saving images in database, pics are displayed in GridView.


To know how to display images in gridview from database, read my post mentioned below
Display Images In GridView From DataBase in ASP.NET C# VB.NET


Html markup of the page look like
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server" Width="95px">
</asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Label ID="lblMessage" runat="server">
</asp:Label>
<asp:Button ID="btnUpload" runat="server" 
            OnClick="btnUpload_Click" Text="Upload"/>
</div>
</form>

Write this code in Click Event of Upload Button
C# Code behind
protected void btnUpload_Click(object sender, EventArgs e)
{
 string strImageName = txtName.Text.ToString();
 if (FileUpload1.PostedFile != null && 
     FileUpload1.PostedFile.FileName != "")
  {
   byte[] imageSize = new byte
                 [FileUpload1.PostedFile.ContentLength];
  HttpPostedFile uploadedImage = FileUpload1.PostedFile;
  uploadedImage.InputStream.Read
     (imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);

 // Create SQL Connection 
  SqlConnection con = new SqlConnection();
  con.ConnectionString = ConfigurationManager.ConnectionStrings
                         ["ConnectionString"].ConnectionString;

 // Create SQL Command 

 SqlCommand cmd = new SqlCommand();
 cmd.CommandText = "INSERT INTO Images(ImageName,Image)" +
                   " VALUES (@ImageName,@Image)";
 cmd.CommandType = CommandType.Text;
 cmd.Connection = con;

 SqlParameter ImageName = new SqlParameter
                     ("@ImageName", SqlDbType.VarChar, 50);
 ImageName.Value = strImageName.ToString();
 cmd.Parameters.Add(ImageName);

 SqlParameter UploadedImage = new SqlParameter
               ("@Image", SqlDbType.Image, imageSize.Length);
 UploadedImage.Value = imageSize;
 cmd.Parameters.Add(UploadedImage);
 con.Open();
 int result = cmd.ExecuteNonQuery();
 con.Close();
 if (result > 0)
 lblMessage.Text = "File Uploaded";
 GridView1.DataBind();
 }
}

VB.NET Code
Protected Sub btnUpload_Click
(ByVal sender As Object, ByVal e As EventArgs)

    Dim strImageName As String = txtName.Text.ToString()
    If FileUpload1.PostedFile IsNot Nothing AndAlso 
       FileUpload1.PostedFile.FileName <> "" Then

        Dim imageSize As Byte() = New Byte
          (FileUpload1.PostedFile.ContentLength - 1) {}

        Dim uploadedImage__1 As HttpPostedFile = 
                                 FileUpload1.PostedFile

        uploadedImage__1.InputStream.Read(imageSize, 0, 
              CInt(FileUpload1.PostedFile.ContentLength))
        
        ' Create SQL Connection 
        Dim con As New SqlConnection()
        con.ConnectionString = 
                 ConfigurationManager.ConnectionStrings
                  ("ConnectionString").ConnectionString
        
        ' Create SQL Command 
        
        Dim cmd As New SqlCommand()
        cmd.CommandText = "INSERT INTO Images
           (ImageName,Image) VALUES (@ImageName,@Image)"
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        
        Dim ImageName As New SqlParameter
                  ("@ImageName", SqlDbType.VarChar, 50)
        ImageName.Value = strImageName.ToString()
        cmd.Parameters.Add(ImageName)
        
        Dim UploadedImage__2 As New SqlParameter
            ("@Image", SqlDbType.Image, imageSize.Length)
        UploadedImage__2.Value = imageSize
        cmd.Parameters.Add(UploadedImage__2)
        con.Open()
        Dim result As Integer = cmd.ExecuteNonQuery()
        con.Close()
        If result > 0 Then
            lblMessage.Text = "File Uploaded"
        End If
        GridView1.DataBind()
    End If
End Sub


Hope this helps

You can download the sample code from this post


Other ASP.NET and GridView articles:

ASP.NET Edit or update multiple records/rows in gridview with checkbox

Delete multiple rows records in Gridview with checkbox and confirmation

LinkButton in GridView and QueryString in ASP.NET to pass/transfer variable and data

Highlight gridview row on mouse over using javascript in asp.net and C# c-sharp

Read write word document with FileStream StreamWriter

121

Display Images In GridView From DataBase Asp.Net

In this example i am explaining how to Show Display Images In GridView From DataBase In ASP.NET Using C# And VB.NET or showing images stored or saved in SQL Server database in gridview,For this i've already stored images in Database.

Table schema is shown below, ID column is primary key with Identity increment,datatype of Image column is Binary.

Display Images In GridView From DataBase Asp.Net
To know how to save or store Images in DataBase visit link below

Upload/Save Images in Database using FileUpload Control in ASP.NET C# VB.NET


For displaying images in gridview we need to create a Handler to read binary data from database.
Right click on solution explorer and Add new item, Pick Generic Handler and name it Handler.ashx.
Write this code in ProcessRequest method
C# code behind
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class Handler : IHttpHandler {
    
public void ProcessRequest (HttpContext context) 
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings
                      ["ConnectionString"].ConnectionString;

// Create SQL Command 
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select ImageName,Image from Images" + 
                  " where ID =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;

SqlParameter ImageID = new SqlParameter
                    ("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Image"]);
dReader.Close();
con.Close();
}

VB.NET Code
Public Class Handler
    Implements IHttpHandler
    
Public Sub ProcessRequest(ByVal context As HttpContext)
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings
                        ("ConnectionString").ConnectionString
        
        ' Create SQL Command 
        
        Dim cmd As New SqlCommand()
        cmd.CommandText = "Select ImageName,Image from Images" +
                          " where ID =@IID"
        cmd.CommandType = System.Data.CommandType.Text
        cmd.Connection = con
        
        Dim ImageID As New SqlParameter
                             ("@IID", System.Data.SqlDbType.Int)
        ImageID.Value = context.Request.QueryString("ID")
        cmd.Parameters.Add(ImageID)
        con.Open()
        Dim dReader As SqlDataReader = cmd.ExecuteReader()
        dReader.Read()
        context.Response.BinaryWrite
                    (DirectCast(dReader("Image"), Byte()))
        dReader.Close()
        con.Close()
    End Sub
End Class

Now drag a GridView control on the aspx page and add SQLDataSource to it.

For configuring GridVIew with SqlDataSource read
Insert Delete Update records in GridView using SqlDataSource ItemTemplate and EditItemTemplate

Now go to html markup of GridView and add a TemplateField and in ItemTemplate add a Image control to display Images.
Html Source of GridView should look like this
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" 
                InsertVisible="False" ReadOnly="True"
                               SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName" 
                               SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
           ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [ImageName], [Image] 
              FROM [Images]"></asp:SqlDataSource>

For VB.NET there is slight change in html markup of page
change below mentioned line
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>

to

ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")%>'/>

THis is how it will look

If you want to display Images in multiple columns or in more than one clumns of GridView then u need to make changes in the code as mentioned below.

1. Add a new column in database (i've named it Image2)
2. Add one mote Template Field in html source of gridview and change source as below
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=1"%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image2">
<ItemTemplate>
<asp:Image ID="Image2" runat="server" 
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=2"%>'/>
</ItemTemplate>
</asp:TemplateField>

And make these changes in code behind of handler.ashx
//Add this line of code in handler.ashx
int intImg = Convert.ToInt32(context.Request.QueryString["img"]);
//Now change earlier code to this one 
SqlDataReader dReader = cmd.ExecuteReader();
        dReader.Read();
        if (intImg == 1)
        {
            context.Response.BinaryWrite((byte[])dReader["Image"]);
        }
        else if (intImg == 2)
        {
            context.Response.BinaryWrite((byte[])dReader["Image2"]);
        }
        dReader.Close();
        con.Close();
Now it will look like this


hope this helps.

Download sample code attached

Sample code for displaying Images in Multiple columns




Other GridView articles:
ASP.NET Display Images in Gridview/DataList using objectdatasource

ASP.NET Insert Edit Update GridView with ObjectDataSource

Add AutoNumber Column in GridView or DataList

Creating Shopping cart in ASP.NET C# VB.NET Example using DataList GridView

Ajax autocomplete extender textbox in EditItemTemaplate of GridView

8

PageMethods Is Undefined ASP.NET AJAX

If you are getting PageMethods Is Undefined Error while using AJAX in ASP.NET or using a webservice than you need to check these things to resolve the issue

1. PageMethods needs to be static

[WebMethod]
public static int MethodName()
{
}


2. Enable pageMethods in scriptManager

<asp:ScriptManager ID="ScriptManager1" runat="server" 
                   EnablePageMethods="true">
</asp:ScriptManager>

3. add reference to script service in code behind
Add [Microsoft.Web.Script.Services.ScriptMethod] or [System.Web.Script.Services.ScriptService] in code behind below [WebMethod]

WebMethod] 
[Microsoft.Web.Script.Services.ScriptMethod]
public static string GetRecords()  
{  
//DO something  
}



Hope this helps

78

Crystal Reports In ASP.NET

This example shows how to Create Crystal Reports In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. I am generating Crystal report by fetching data from two tables and grouping them based on Project Name. Database tables are just for demo purpose you can create your own tables with whatever schema you want

Two tables are as shown below.

Crystal reports in ASP.NET

Create a new website and right click on solution explorer > add new Item > Select Crystal Report
In the dialog box choose blank report.

 
Now click on CrystalReports Menu in VS and select DataBase Expert 
  
In database expert dialog box expend create new connection > OLEDB(ADO) section
 
Now select SQL Native client and enter you SQL server address , username , password and pick database name from the dropdown. 
 
  
In next screen Expend your database objects in left pane and add the tables you want to use in right pane 
 
Link your tables based on Primary keys (If any)

Click ok to finish the wizard.
Right click on Field Explorer and select Group Name Fields  > Insert Group

In next box select the field you to report to be grouped (in my case it's ProjectsName)

Click on OK to finish
Now design the report , drag and fields from Database fields in field explorer and which you want to show in report and drop them in Section3(Details), and preview the report, it should look like show below.


Go to default.aspx page and drag and drop CrystalReportViewer from the toolbox, click on smart tag and choose new report source.
Choose you report from the dropdown menu and click ok to finish.
Now when you build and run the sample , it asks for the database password everytime.

 
To fix this we need to load the report programmatically and provide username and password from code behind .
Now run the report , it should look like this 


Html markup of default.aspx look like
<form id="form1" runat="server">
<div>
  <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>
    
    </div>
    </form>

C# code behind

Write this code in the event you find appropriate , i m writing it in Page_Load , you can write this code in click event of button or in pagePreRender event
The code to provide password programmatically.
protected void Page_Load(object sender, EventArgs e)
    {
        ReportDocument crystalReport = new ReportDocument();
        crystalReport.Load(Server.MapPath("CrystalReport.rpt"));
        crystalReport.SetDatabaseLogon
            ("amit", "password", @"AMIT\SQLEXPRESS", "TestDB");
        CrystalReportViewer1.ReportSource = crystalReport;
    }

VB.NET code behind
Protected Sub Page_Load
(ByVal sender As Object, ByVal e As EventArgs)

Dim crystalReport As New ReportDocument()

crystalReport.Load(Server.MapPath("CrystalReport.rpt"))

crystalReport.SetDatabaseLogon
("amit", "password", "AMIT\SQLEXPRESS", "TestDB")

CrystalReportViewer1.ReportSource = crystalReport

End Sub

Hope this helps


related posts :
Crystal Reports in Winforms Windows Forms with Parameters C#.NET VB.NET

SubReports in Crystal Reports in ASP.NET

Find More Articles