简体   繁体   中英

how to populate items from database in a listbox in vb.net

I was developing an application using oop concept.I have a class that has 2 attributes and have Get and Set methods namely WorkItemNumber and Description.

On the client side i have a list box used to populate the work items based on their description.Here's the code i wrote in the class o read items from the database.

Public Sub LoadWorkItem()
    ' Load the data.
    ' Select records.
    Dim oWorkItem As WorkItem = New WorkItem()
    Dim conn As New OleDbConnection
    Dim data_reader As OleDbDataReader
    conn = oWorkItem.GetDbConnection()
    Dim cmd As New OleDbCommand("SELECT * FROM work_item ORDER BY [work item number]", conn)
    data_reader = cmd.ExecuteReader()
    'ListBox1.Items.Clear()
    If data_reader.HasRows = True Then
        Do While data_reader.Read()
            WorkItemNumber = data_reader.Item("work item number")
            Description = data_reader.Item("description")
        Loop
    End If
    data_reader.Close()
    data_reader = Nothing
    cmd.Dispose()
    cmd = Nothing
    conn.Close()
    conn.Dispose()
End Sub

How do i populate the listbox using the code,and if there's any improvement on the code please do tell me as well.Thank you

To poulate your ListBox, do this...

ListBox1.Item.Clear()
If data_reader.HasRows Then
    Do While data_reader.Read()
        WorkItemNumber = data_reader.Item("work item number")
        Description = data_reader.Item("description")
        ListBox1.Items.Add(New ListItem(Description, WorkItemNumber)
    Loop
End If

As far as improvements, start by using a Using statement for the DB connection. In your code, if there is an exception while the database connection is open, it will never get closed. This is better...

Using conn As OleDbConnection = oWorkItem.GetDbConnection()
    ' Execute SQL and populate list... 
End Using

The above code assures that your connection will be closed.

Then, turn on Option Strict and Option Explicit . This will force you to declare the Type for Description and WorkItemNumber and cast them as Strings when adding a ListItem. This will reduce run-time errors.

Finally, if this is anything but a small app you are doing as a learning experiment, you should read up on tiered application design . Your code is mixing UI, business logic, and data access in the same method. This is generally frowned upon.

  • Your "user interface" LoadWorkItem() method should ask a "core" method for a list of WorkItems.
  • Your core method should then ask a "data access" method for data.
  • The "data access" method should make the call to the database.

Happy coding.

Update: You can find excellent info about n-Tier architecture on MSDN . A good book to read once you grasp the fundamentals and have some confidence in .NET is Visual Basic .NET Business Objects .

    Imports System.Data.SqlClient 'Reference The Sql Client

    Public Class Form1
   ''Make sure to change the connection string below to your connection string this code only works for SQL DataBase. If Your connection String is wrong This will Not Work

    Dim connString As String = "Data         
    Source=NameofYourSQLServer\SQLEXPRESS;Initial Catalog=NameOfYourDataBase;Integrated Security=True"

Dim tblDIV As DataTable
Dim daDIV As SqlDataAdapter
Dim dsDIV As New DataSet
Dim oCon As SqlConnection

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim oCon = New SqlConnection
     oCon.ConnectionString = connString
     dsDIV = New DataSet

  ' Select all Fields and order by ID or Replace * with name of Field

   daDIV = New SqlDataAdapter("SELECT * FROM NameOfYourTable ORDER BY Id DESC", oCon)
    '*** Define command builder to generate the necessary SQL
    Dim builder As SqlCommandBuilder = New SqlCommandBuilder(daDIV)
    builder.QuotePrefix = "["
    builder.QuoteSuffix = "]"

    Try
        daDIV.FillSchema(dsDIV, SchemaType.Source, "DIV")
        daDIV.Fill(dsDIV, "DIV")
        tblDIV = dsDIV.Tables("DIV")
        ListBox1.DataSource = tblDIV
        ListBox1.DisplayMember = "NameOfTheFieldYouWanttoDisplay"
    Catch ex As Exception

        MsgBox("Encountered an Error;" & vbNewLine & ex.Message)

        oCon.Close()

    End Try
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM