Reuse your .net code - Part 1

Please support our VB.NET advertiser: Intel Parallel Studio Home
Jadranko Dragoje ManicCW is offline Offline | Sep 11th, 2006, 3:21 am |
0
When you are programming web pages it is very important to optimize your code for better and faster performance. In this part I will show you how to optimize code for filling multiple dropdownlists with data from Microsoft Access. The same thing is with SQL Server. I'm using asp.net 2.0 and Microsoft Visual Studio 2005.

Add new Module to your project and name it DataOperations (Right Click Project - Add New Item - Class. Change class to module, like this:

  1. Public Module DataOperations
  2.  
  3. End Module

Now write code for filling dropdownlist:

  1. Imports System.Data.OleDb
  2. Imports System.Configuration.ConfigurationManager
  3.  
  4. Public Module DataOperations
  5.  
  6. Public Sub FillDropDown(ByVal ddl As DropDownList, ByVal tbl As String, ByVal txt As String, ByVal val As String)
  7. Dim cn As New OleDbConnection(ConnectionStrings("Data").ConnectionString.ToString)
  8. Dim cmd As New OleDbCommand
  9. cmd.CommandType = Data.CommandType.Text
  10. cmd.Connection = cn
  11. cmd.CommandText = "SELECT " & val & ", " & txt & " FROM " & tbl & " ORDER BY " & txt & " ASC"
  12. Dim dr As OleDbDataReader
  13. cn.Open()
  14. dr = cmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
  15. While dr.Read
  16. ddl.Items.Add(New ListItem(dr(txt).ToString.Trim, dr(val)))
  17. End While
  18. dr.Close()
  19. End Sub
  20.  
  21. End Module

Now all you need to do to fill dropdownlist is to call this sub like:

  1. FillDropDown(Me.cmbCategory, "Categories", "Category", "ID")

You need to pass parameters: dropdown name, table or query for fill, table column for text and table column for value.
If you need you can expand this sub by adding where and order by parameters.

Hope this helps.
Quick reply to this message  

Tags
access, code, combo, data, dropdownlist, module, net, reuse, web

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC