Mohammed Atef’s Technical blog

Create Generic Collection with Generic Binding Method for Dropdown List

Introduction

At this post i am going to show you how to create generic collection class with generic method for binding any Dropdown List.

Solution

I will describe my code in steps as follows

Step one Create Generic class

here we will create generic class as shown below

   1: Imports Microsoft.VisualBasic
   2: Public Class GenericCollection(Of T)
   3:     Inherits CollectionBase
   4:     Public Function Add(ByVal value As T) As Integer
   5:         Return List.Add(value)
   6:     End Function
   7:     Public Sub Remove(ByVal value As T)
   8:         List.Remove(value)
   9:     End Sub
  10:     Public ReadOnly Property Item(ByVal index As Integer) As T
  11:         Get
  12:             Return CType(List.Item(index), T)
  13:         End Get
  14:     End Property
  15: End Class

In the above code you need to note the below step:

1- Our class inherits from CollectionBase

2- Add method take any kind of object T and add it to collection list

3- Remove method delete kind of object T and remove it from collection list

4- Item property return object of T

Step two Create Generic Method to Bind any Dropdown List

find code for this method here

   1: Public Shared Sub FillDDL(ByRef ddl As DropDownList, ByVal col As CollectionBase, ByVal strval As String, ByVal strname As String)
   2:         ddl.DataSource = col
   3:         ddl.DataTextField = strname
   4:         ddl.DataValueField = strval
   5:         ddl.DataBind()
   6:     End Sub

I think any one can understand the above code but note that col parameter is from try collectionbase to path any type of object class.

Step Three how to use this code

find code for using Generic class and method

   1: Dim col As GenericCollection(Of Priority) = priorityprov.GetAllPrioritysGeneric()
   2: CtrlHelper.FillDDL(ddlpriority, col, "PriorityID", "PriorityArName")

in the above code assume the following

1- CtrlHelper is the class which contain FillDDL generic method

2- GetAllPrioritysGeneric() is method return genericcollection of type Priority

conclusion

at the end now you have common class for any collection and common method for binding any Dropdown List in any solution.

I hope this helped

Advertisements

October 6, 2009 - Posted by | Asp.net, C#,VB.Net | ,

1 Comment »

  1. Thank Khalid for you Comment to replace byval to byref to solve performance issue.

    Comment by mohammedatef83 | October 7, 2009 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: