Creating Custom GridView Control
page 1 of 6
Published: 17 Nov 2008
Abstract
In this article, Abdulla examines the creation of a new custom GridView control from scratch, which allows the developer to include a checkbox column to the GridView control automatically with embedded JavaScript code to check/uncheck the checkbox column without the need to write any bit of code. He begins with comprehensive coverage of the steps involved in customization of the GridView class and implementation of template classes. Towards the end of the article, Abdulla examines the usage of the control with Visual Studio 2005. The article also covers how to embed a JavaScript file with a custom control and how to use it later on with the help of detailed analysis, relevant source code, and screenshots.
by Abdulla Hussein AbdelHaq
Feedback
Average Rating: 
Views (Total / Last 10 Days): 47865/ 40

Customizing the GridView Class

I recommend that you download the source code from the link given at the end of the article, which contains the code of the custom control with a sample website; you can look at it in more details.

Let us begin creating our new custom GridView control, open your Visual Studio then create a new Class library project and name it as "MyCustomControl."

First of all, you have to add some references to allow you to use the needed namespaces and classes, below are the needed references:

1.    System.Design

2.    System.Drawing

3.    System.Web 

4.    System.Web.Extensions 

5.    System.Web.Extensions.Design

Then create a new class and name it "CustomGrid."

Inheriting the GridView class is much better than creating a new databound control from scratch, that give us the benefits of functions and subroutines already existing in the GridView class.

Listing 1

<Assembly: TagPrefix("MyCustomControl.CustomsControls", "asp")> 
<Assembly: WebResource("MyCustomControl.CustomGridJS.js", "text/javascript")> 
Namespace CustomsControls
<ToolboxData("<{0}:CustomGrid runat=""server""></{0}:CustomGrid>")> _
Partial Public Class CustomGrid
Inherits GridView
'My Code Here
End Class

We will create a property for including the checkbox column to allow the developer to add the column automatically, which is implemented in Listing 2.

Listing 2

''' <summary>
''' Add checkbox column to the gridview.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<Category("Behavior")> _
          <Description("Add checkbox column to the gridview.")> _
          <DefaultValue(False)> _
          Public Property IncludeColumnCheckBox() As Boolean
  Get
  If String.IsNullOrEmpty(ViewState("IncludeColumnCheckBox")) Then
    Return False
  Else
    Return DirectCast(ViewState("IncludeColumnCheckBox"), Boolean)
  End If
  End Get
  Set(ByVal Value As Boolean)
  ViewState("IncludeColumnCheckBox"= Value
  End Set
End Property

Now we will override the CreateColumns function which is responsible for creating the columns, and there we will add our new checkbox column, as in Listing 3.

Listing 3

Protected Overrides Function CreateColumns(ByVal dataSource As PagedDataSource, _
ByVal useDataSource As BooleanAs ICollection
Dim columnList As ICollection = MyBase.CreateColumns(dataSource, useDataSource)
  If Not IncludeColumnCheckBox Then
    Return columnList
  End If
  Dim list As ArrayList = New ArrayList(columnList)
  Dim _CheckBoxColumn As New MyTemplateField
  list.Insert(0, _CheckBoxColumn)
  Return list
End Function

You may note that I am declaring an object from a template class that I created before I called MyTemplateField, and that the GridView column consisted from the set of templates classes (Header, Item, Alternate and footer).

I will illustrate these templates classes in the Implementing Templates classes section,

Developers do not need to write multi lines of code to get the ID's of the selected rows; we will return these ID's simply by writing a new property called GetCheckedRows which is shown below.

Listing 4

''' <summary>
''' Return list of IDs joined with ',' separators
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<Browsable(False)> _
           Public ReadOnly Property GetCheckedRows() As String
  Get
  Dim _collectionIds As String = String.Empty
  If DataKeys.Count > 0 Then
 
    For i As Integer = 0 To Rows.Count - 1
      If Rows(i).RowType = DataControlRowType.DataRow Then
        If DirectCast(Rows(i).FindControl("ChkItem"), CheckBox).Checked Then
          If _collectionIds = String.Empty Then
            _collectionIds = DataKeys(Rows(i).RowIndex).Value
          Else
            _collectionIds & = "," & DataKeys(Rows(i).RowIndex).Value
          End If
        End If
      End If
    Next
  End If
  Return _collectionIds
  End Get
End Property

View Entire Article

User Comments

Title: ss   
Name: aa
Date: 2012-10-31 2:45:13 AM
Comment:
sa sa adsdasad asdas
Title: Nice Article   
Name: Nguyen Van Tai
Date: 2010-08-10 12:24:23 PM
Comment:
This article is very nice. Thanks so much!
Title: Re: Build Error   
Name: Abdulla [The Author]
Date: 2010-01-09 5:25:17 PM
Comment:
Hello Rafael,
it seems that you do not have ajax extensions on your pc.
if you are,then download it and add the below dlls

1. System.Design

2. System.Drawing

3. System.Web

4. System.Web.Extensions (this is for AJAX)

5. System.Web.Extensions.Design (This is for AJAX)
Title: build error   
Name: Rafael
Date: 2010-01-08 11:24:32 AM
Comment:
Thanks for sharin good article. I am new to asp.net. I have downloaded your source in Visual studio 2008 and while compiling it is throwing with "script manager is not declared" and 4 warning msgs. Just guide me. I appreciate.

Thanks
Rafael
Title: Developer   
Name: Amit
Date: 2009-12-17 12:44:01 AM
Comment:
This is a very good article. Thanks for posting it and sharing your knowledge.

Amit
Title: Re: Custom Control   
Name: Abdulla [Author]
Date: 2009-11-26 9:32:24 AM
Comment:
Hello Siva,
open the custom control project, build it with zero errors.
and then to add the dll to your toollbox, follow the below instructions:
Right click on the toolbox window then choose "Add Tab."

Type the name you want for the new tab, right click over it, and click "Choose Items."

Click on the Browse button in the ".NET Framework Components" tab, go to the custom GridView project, open the bin folder, and choose MyCustomControl.dll.
Title: Custom Control   
Name: Siva
Date: 2009-11-26 6:23:50 AM
Comment:
I cannot find custom control and custom grid view in my toolbox. Please help me......
Title: Extra feature Needed !! Please help Abdulla   
Name: anji
Date: 2009-10-26 9:31:02 PM
Comment:
Abdulla ,
u r idea works excellent.what if i want to include an extra header row with all checkboxes in it .And click of each check box in each column header will rise an event.

please,can u give to modifications to ur code to include above said functionality and include as a separate article or mail the file to anji.halaharvi@gmail.com
Title: Need code in C#   
Name: DJ
Date: 2009-08-07 6:42:45 AM
Comment:
Hi
Can u convert all code to C#
Title: Re: Can u convert all code to C#   
Name: Abdulla [The Author]
Date: 2009-08-05 2:09:32 PM
Comment:
Well, I am a Visual Basic Developer.
C# or VB it does not matter, the major point is the idea, there are many tools and websites that enable you to convert code between two languages
Title: Can u convert all code to C#   
Name: Aziz
Date: 2009-08-05 10:36:58 AM
Comment:
if you can, please convert to C# your source.
Title: Applications Programmer   
Name: JHG
Date: 2009-07-07 11:18:20 AM
Comment:
Grr. Visual Basic again!
Title: Hello   
Name: Jilani
Date: 2009-07-07 8:48:22 AM
Comment:
This is nice Art
Title: Mr   
Name: Thanigainathan
Date: 2009-07-07 8:26:09 AM
Comment:
Hi,

This article is very nice. Thanks for giving this opportunity to read this. This will be the base to create advanced controls.

Thanks,
Thani
Title: No Website Code RegisterClient   
Name: User
Date: 2009-06-29 6:02:19 PM
Comment:
Abdulla thanks for the great article this was a great learning point. Unfortunetly I've been getting the following errors.

The ScriptManager.RegisterStartupScript line in "Public Overrides Sub Rendercontrol" method doesn't compile. I had to change it to "Page.ClientScript.RegisterClientScriptBlock"

This line in the onRowCreate "DirectCast(e.Row.FindControl("ChkHeader"), CheckBox).Attributes.Add("onclick", _
"ObjJs_" & Me.ID & ".CheckUnCheckRows(this.checked)")" produces an undefined object when the header checkbox is clicked. Have not been able to solve this one.

I also was unable to find the sample site in the download.
Title: SampleWebsite code missing   
Name: Michael
Date: 2009-06-26 10:05:57 AM
Comment:
Hi there, I'm experiencing the same as Mouzam. There doesn"t appear to any Sample Website code files.

Has this issue been resolved yet?

I tried pasting in the error messages but the result is my previous post.
Title: Extremely Helpful   
Name: Faisal Lodhi
Date: 2009-05-21 6:18:17 PM
Comment:
Thank you for this article, it was much easier to read and understand than so many others that explain how to inherit from GridView
Title: SampleWebsite code missing   
Name: Mouzam
Date: 2009-05-01 10:59:21 AM
Comment:
Hi, a nice simple article. But the SampleWebsite source is missing. I used this link to download (http://authors.aspalliance.com/AAbdelHaq/TestingCustomGridView.zip). CustomGrid source is available but SampleWebsite code is not.
Title: Re: Ms   
Name: Abdulla [The Author]
Date: 2009-03-15 3:14:08 PM
Comment:
Are you sure ? I just downloaded the project successfully !
Please try again, and report us if it is still not working.
Title: Ms   
Name: Diana
Date: 2009-03-13 4:55:58 AM
Comment:
Gr8 article....
But unable to download the sample.
Title: Excellent Article   
Name: Cebo
Date: 2008-11-20 2:20:05 PM
Comment:
This article of example project of gridview with checkbox is very well written and deserves 5-stars!

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-18 9:10:11 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search