列表框数据库

时间:2013-02-25 15:13:46

标签: vb.net datagridview listbox

好的,对于一个项目,我不允许使用Datagridview,而是在搜索时我必须使用Listbox来显示数据库中的数据。我将链接下面的代码,有人可以告诉我如何更改此代码以适应列表框。我是编程的小伙子,所以如果我犯了任何明显的错误,请原谅我

导入System.Data Imports System.Data.OleDb 公共类frmUserList

Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
    Me.Close()
End Sub
Private Sub Load_Record()
    Dim conn As New OleDbConnection
    Dim cmd As New OleDbCommand
    Dim da As New OleDbDataAdapter
    Dim dt As New DataTable
    Dim sSQL As String = String.Empty

    'try catch block is used to catch the error
    Try
        'get connection string declared in the Module1.vb and assing it to conn variable
        conn = New OleDbConnection(Get_Constring)
        conn.Open()
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        sSQL = "SELECT user_id,  last_name + ', ' + first_name + ' ' + mid_name as name FROM users where last_name + ', ' + first_name + ' ' + mid_name like '%" & Me.txtSearch.Text & "%' or [first_name] = '" & Me.txtSearch.Text & "'"

        cmd.CommandText = sSQL
        da.SelectCommand = cmd
        da.Fill(dt)

        Me.dtgResult.DataSource = dt
        If dt.Rows.Count = 0 Then
            MsgBox("No record found!")
        End If

    Catch ex As Exception
        MsgBox(ErrorToString)
    Finally
        conn.Close()
    End Try
End Sub

Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
    Load_Record()
End Sub

Private Sub dtgResult_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtgResult.DoubleClick
    If Me.dtgResult.SelectedRows.Count > 0 Then
        Dim frm As New frmMarkSeat
        frm.txtFname.Tag = Me.dtgResult.Item(0, Me.dtgResult.CurrentRow.Index).Value
        frm.ShowDialog()
        frm = Nothing
    End If
End Sub

结束班

1 个答案:

答案 0 :(得分:0)

尝试使用SQLDataReader :(未经测试的代码,只是无法写出来)。

'start here
conn.Connection.Open()
Dim sqlDR As SqlDataReader
Dim colValue As String

 sqlDR = conn.ExecuteReader
 While sqlDR.Read
   colValue = (sqlDR.GetValue(0)).ToString
   ItemlistBox.Items.Add(colValue)
   ItemlistBox.Sorted = True
 End While

 conn.Connection.Close()

或者您可以继续使用当前对象,使用其他对象DataSet并填充列表框。

Dim dtset As New DataSet
Dim da As New OleDbDataAdapter

da.Fill(dtset)
ItemListBox.DataSource = dtset
ItemListBox.DisplayMember = "ColName"