How to Load Data From SQL Server Into Combo Box in VB.Net

Respons: 1 comments

How to Load Data From SQL Server Into Combo Box in VB.Net


How to populate a filed from sql server database table into combo box in vb.net.

Here is Example

Just a create public function in any module as follows

  Public Sub LoadDataIntoComboBox(ByVal SQLStr As String, ByVal cob As ComboBox, ByVal FieldName As String, Optional ByVal AnyExtraItem As String = "")  
     Dim SqlConn As New SqlClient.SqlConnection  
     Dim Sqlcmmd As New SqlClient.SqlCommand  
     Try  
       SqlConn.ConnectionString = ConnectionStrinG  
       SqlConn.Open()  
       Sqlcmmd.Connection = SqlConn  
       Sqlcmmd.CommandText = SQLStr  
       Sqlcmmd.CommandType = CommandType.Text  
       Dim Sreader As SqlClient.SqlDataReader  
       Sreader = Sqlcmmd.ExecuteReader  
       cob.Items.Clear()  
       While Sreader.Read()  
         cob.Items.Add(Sreader(FieldName).ToString.Trim)  
       End While  
       If AnyExtraItem.Trim.Length > 0 Then  
         cob.Items.Add(AnyExtraItem)  
       End If  
       Sreader.Close()  
       Sreader = Nothing  
     Catch ex As Exception  
       MsgBox(ex.Message)  
     Finally  
       SqlConn.Close()  
       SqlConn.Dispose()  
       Sqlcmmd.Connection = Nothing  
     End Try  
   End Sub  

How to load data using above subroutine

Example 1
LoadDataIntoComboBox("Select distinct empname from payrolldata", comboboxname, "Empname")

Example 2
LoadDataIntoComboBox("Select * from Categoriesgroups", comboboxname, "StockCategoryName")


The above two examples , the data loads into the "comboboxname"




1 comment:

Copyright © MS SQL MS-ACCESS

Sponsored By: GratisDesigned By: Habib Blog