Insert an Image in between Rows of a GridView using ASP.NET

Posted by: Suprotim Agarwal , on 5/10/2008, in Category ASP.NET
Views: 60790
Abstract: At times, you need to perform these custom routines, to add your own data, when the data is being bound to a GridView control. In this article, we will explore how to insert image or text in between the rows of a GridView. We will also see how we can create new rows on the fly and attach them to the GridView control at runtime.
Insert an Image in between Rows of a GridView using ASP.NET
 
At times, you need to perform these custom routines, to add your own data, when the data is being bound to a GridView control. In this article, we will explore how to insert image or text in between the rows of a GridView. We will also see how we can create new rows on the fly and attach them to the GridView control at runtime. Follow these steps:
Step 1: Create a new ASP.NET website. Drag and drop a SqlDataSource Control to the page and use the wizard to connect to the Northwind database. Select the CustomerId, CompanyName, ContactName, Address and City from the Customers table. The wizard will also prompt you to save the connection string in the web.config file. Choose to do so. The design code will look similar to the following:
      <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
        </asp:SqlDataSource>
An entry will be added to the web.config file as shown below:
      <connectionStrings>
            <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
      </connectionStrings>
Step 2: Now add a GridView control to the page and using the smart tag, select the DataSource to be SqlDataSource1 in the GridView tasks panel. Using the same panel, click on the Enable Paging and Enable Sorting checkboxes. The source will look similar to the following.
       <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1"
            OnRowDataBound="GridView1_RowDataBound" Font-Names="Verdana" Font-Size="Small">
            <Columns>
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            </Columns>
        </asp:GridView>
Step 3: We will now need to think of a way to add our own custom row with the image, in between the existing rows of a GridView. The GridView renders as a table and contains rows and cells. If we could somehow create a cell on the fly, add our image to the cell and then add the cell to the row, we should be able to achieve our requirement. All this needs to be done while the row is being bound to data in the GridView control. Well the event that we will make use of to perform all the action, is the GridView_RowDataBound event. This event enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs. Before that, add a page level variable called pgSize which will hold the row position at which we need to insert the image. Also add an image to your project that is about the same width as that of your GridView. The comments have been marked inside the code to help you understand. The entire code will look similar to the following:
C#
public partial class _Default : System.Web.UI.Page
{
    static int pgSize;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
              pgSize = 0;
    }
 
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TableCell tCell = new TableCell();
            // create image
            Image img = new Image();
            img.ImageUrl = "subheader.jpg";
            // add the image to the cell
            tCell.Controls.Add(img);
           
            GridView gView = (GridView)sender;
            // set the colspan to occupy the other cells in the row
            int colSpan = gView.Columns.Count;
            tCell.Attributes["ColSpan"] = colSpan.ToString();
 
            GridViewRow gRow = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
            // add the cells to the gridviewrow
            gRow.Cells.Add(tCell);
 
            Table tbl = (Table)e.Row.Parent;
 
            // set the pagesize initially to the pagecount/2
            // in our case it is 10/2 = 5. So the first image will
            // displayed after the 5th row.
            if(pgSize == 0)
                pgSize = GridView1.PageCount / 2;
 
            // This step is performed so that we can display the image only after every
            // 5, 15, 25 ,35 rows and so on ...
            // The logic is not perfect but will give you the idea
            if (Convert.ToDouble(e.Row.DataItemIndex + 1) / Convert.ToDouble(pgSize) == 1.0)
            {
                tbl.Controls.AddAt(gView.Controls[0].Controls.Count, gRow);
                // add 10 to the pgsize so that the image can be displayed
                // at rows 5, 15, 25 and so on..
                pgSize = pgSize + 10;
            }
        }
    }
}
 
VB.NET
Public Partial Class _Default
      Inherits System.Web.UI.Page
      Private Shared pgSize As Integer
 
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If (Not Page.IsPostBack) Then
                   pgSize = 0
            End If
      End Sub
 
      Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.DataRow Then
                  Dim tCell As TableCell = New TableCell()
                  ' create image
                  Dim img As Image = New Image()
                  img.ImageUrl = "subheader.jpg"
                  ' add the image to the cell
                  tCell.Controls.Add(img)
 
                  Dim gView As GridView = CType(sender, GridView)
                  ' set the colspan to occupy the other cells in the row
                  Dim colSpan As Integer = gView.Columns.Count
                  tCell.Attributes("ColSpan") = colSpan.ToString()
 
                  Dim gRow As GridViewRow = New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
                  ' add the cells to the gridviewrow
                  gRow.Cells.Add(tCell)
 
                  Dim tbl As Table = CType(e.Row.Parent, Table)
 
                  ' set the pagesize initially to the pagecount/2
                  ' in our case it is 10/2 = 5. So the first image will
                  ' displayed after the 5th row.
                  If pgSize = 0 Then
                        pgSize = GridView1.PageCount / 2
                  End If
 
                  ' This step is performed so that we can display the image only after every
                  ' 5, 15, 25 ,35 rows and so on ...
                  ' The logic is not perfect but will give you the idea
                  If Convert.ToDouble(e.Row.DataItemIndex + 1) / Convert.ToDouble(pgSize) = 1.0 Then
                        tbl.Controls.AddAt(gView.Controls(0).Controls.Count, gRow)
                        ' add 10 to the pgsize so that the image can be displayed
                        ' at rows 5, 15, 25 and so on..
                        pgSize = pgSize + 10
                  End If
            End If
      End Sub
End Class
 
The rendered GridView at the end will look similar to the following
Insert Image In GridView
Well I hope this example has given you some insights of the various possibilities of customizing the GridView to suit our requirements. Keep visiting the site as we will explore more of these ‘unusual’ requirements that you could encounter while dealing with the GridView. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 
 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and the C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Bilal on Thursday, May 22, 2008 3:28 AM
I have tried this but its not working.
The Trick seems good so i am giving yoy the 5 rates.
Comment posted by suprotim agarwal on Thursday, May 22, 2008 11:17 AM
Hi Bilal: Kindly let me know the issue you face while implementing the code. I just checked it again and works just fine.

Thanks
Comment posted by Bilal Haider on Wednesday, June 4, 2008 2:34 AM
pgSize = GridView1.PageCount / 4;
pgSize = pgSize + 2;

I am not getting image after 2 rows.

PMDCRegNumber   HospitalName   PersonalName   BriefProfile   Specialization
113ui   Bilal   Bilal    bilal   Dentist
as   dfasdf   asdf    asdf   asdf
asdas   lkj   lkj    lkj   lk
ii9   bilal   bilal    jjjj   jjjj
Sorry a i was busy regarding my exams i am replying late.
Comment posted by sameer kothari on Friday, July 25, 2008 12:07 AM
its good artical......

its really helpful.
Comment posted by Andrew on Monday, August 4, 2008 1:27 AM
Thanks for the tips Suprotim, helped me a lot...just pointing out an error in your code though.

If pgSize = 0 Then
    pgSize = GridView1.PageCount / 2
End If

should be...

If pgSize = 0 Then
    pgSize = GridView1.PageSize / 2
End If


Cheers!
Comment posted by Michelle on Monday, August 4, 2008 10:55 AM
I think it is PageCount/2. Worked fine for me though!!
Comment posted by P on Monday, August 4, 2008 11:28 PM
hi bilal, can u kindly to give me some tips and guides if i want to retrieve the data from a gridview where the datasource for that gridview is retrieved from a combination of 3 tables in the database?
Comment posted by tony on Thursday, August 14, 2008 4:27 AM
hello suprotim,
this article is superb.but it is not fullfilling my requirement,
i want to add a image at a particular cell in a seperate column of a gridview & i dont want entire row to be occupied,
for example i have binded a customer table into a gridview,
i have one empty column in grid view for image,i want to add image in
that empty column at particular cell,please help me in doing that...........it will be very helpful......
Comment posted by pavanireddy on Tuesday, September 16, 2008 6:51 AM
how to merge columns dynamically in gridview
Comment posted by Ron C. on Wednesday, October 1, 2008 9:06 PM
Great article and exactly what I'm looking for! I've put the VB code in my page exactly as it is here and get the following error both in VWD and when I load the page:
Compiler Error Message: BC30469: Reference to a non-shared member requires an object reference.

Source Error:
Line 39:                 ' displayed after the 5th row.
Line 40:                 If pgSize = 0 Then
Line 41:                     pgSize = GridView1.PageCount / 2
Line 42:                 End If
Line 43:  
Source File: C:\inetpub\wwwroot\hma\cbforms.aspx    Line: 41

Any ideas?

Comment posted by Suprotim Agarwal on Friday, October 3, 2008 11:22 PM
Have you declared pgSize as static/shared?
Comment posted by sunil on Friday, November 14, 2008 1:30 AM
Can we do this with repeater control ???? Pls post code...g8t post...
Comment posted by rahul on Tuesday, November 18, 2008 4:00 PM
can anybody plz tell how to get image after every row of gridview..i am not using paging as i have freeze the gridview header ...thanks in advance
Comment posted by Suprotim Agarwal on Wednesday, November 19, 2008 10:23 AM
Rahul: just change the logic. for example check for i % 2 == 0 to generate alternate image rows.
Comment posted by Mike Jamas on Monday, December 22, 2008 11:21 AM
when the page is clicked again, the image does not show us. say, you have more than two pages, you click on page 2, then go back to page 1, no image show up in page 1. why? any fix?
Comment posted by Ranjan Srivastava on Thursday, December 25, 2008 2:44 AM
Very relaxed
Comment posted by Suprotim Agarwal on Friday, December 26, 2008 9:12 PM
Mike: Let me check if the logic needs to be changed. THanks

Ranjan: Thanks
Comment posted by kiranmayi on Monday, March 2, 2009 11:56 PM
Actually i have tried this but am not getting an image in between rows what i have to do
Comment posted by murthy on Wednesday, July 29, 2009 5:46 AM
I got some idea about that but i want to add a image at a particular row no need the count of 5 10 .......so give  me any help plz..........
Comment posted by murthy on Thursday, July 30, 2009 1:10 AM
I got some idea about that but i want to add a image at a particular row no need the count of 5 10 .......so give  me any help plz..........
Comment posted by David Blu on Thursday, July 30, 2009 3:35 AM
@Murtry: This is should be simple. Instead of the line
if (Convert.ToDouble(e.Row.DataItemIndex + 1) / Convert.ToDouble(pgSize) == 1.0)

Just Check the e.Row.DataItemIndex equals to your desired row and then add the rest of the code.
Comment posted by murthy on Monday, August 3, 2009 7:04 AM
I got some idea about that but i want to add a image at a particular row no need the count of 5 10 .......so give  me any help plz..........
Comment posted by Sobin on Saturday, September 26, 2009 9:51 AM
"when the page is clicked again, the image does not show us. say, you have more than two pages, you click on page 2, then go back to page 1, no image show up in page 1. why? any fix?"

This comment by Mike is not yet answered... Any fix?
Comment posted by jozoa on Thursday, December 22, 2011 9:46 AM
This is a great article. You have no idea how long I have looked for something like this. I have been able to implement a details gridview for each row before but I could never implement it as easily as this. Thanks to your article, I can do it way easier now.
Comment posted by Raju from india on Saturday, May 12, 2012 1:40 AM
very helpful

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook