2013-02-25 67 views
0

好的,所以對於一個項目,我不允許使用Datagridview,相反,我將不得不使用Listbox在搜索時顯示數據庫中的數據。我將在下面鏈接我的代碼,任何人都可以告訴我如何更改此代碼以適應列表框。我是一個小白編程,所以如果我做的任何明顯的錯誤,請原諒我列表框數據庫

進口System.Data 進口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 

末級

回答

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" 
+0

我收到錯誤:System.Data.DataViewManagerListItemTypeDescriptor – user2083368 2013-02-25 15:45:43

+0

**未經測試的代碼**,以及您嘗試過哪些代碼? – bonCodigo 2013-02-25 16:11:53

+0

第二部分 – user2083368 2013-02-25 17:49:38