Load DropDownList from Database in ASP.NET 3.5


/ Published in: ASP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. Sub BindDropDownListDB(ByVal ddlDrop As Object, ByVal strTable As String, ByVal strValue As String, ByVal strText As String, ByVal strOrder As String, ByVal strWhere As String)
  2.  
  3. Dim objConn As New SqlConnection()
  4. Dim objCmd As New SqlCommand()
  5. Dim strSQL As String
  6.  
  7. objConn = New SqlConnection(ConfigurationManager.ConnectionStrings("[database]").ConnectionString)
  8. objCmd.Connection = objConn
  9. objCmd.Connection.Open()
  10.  
  11. strSQL = "SELECT " + strValue + " As Value1, " + strText + " As Text1 "
  12. strSQL += "FROM " + strTable + " "
  13. strSQL += "WHERE " + strWhere + " "
  14. strSQL += "ORDER BY " + strOrder + ";"
  15.  
  16. objCmd.CommandText = strSQL
  17. ddlDrop.DataSource = objCmd.ExecuteReader()
  18. ddlDrop.DataTextField = "Text1"
  19. ddlDrop.DataValueField = "Value1"
  20. ddlDrop.DataBind()
  21. ddlDrop.Items.Insert(0, New ListItem("Default Item", ""))
  22.  
  23. objConn.Dispose()
  24. objConn.Close()
  25.  
  26. End Sub

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.