Can't display Data in ComboBox Control of DropDownStyle (DropDownList)

耗尽温柔 提交于 2020-06-09 04:41:47

问题


I have the following requirement,

I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database Table, and it's working fine.

(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))

But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.

(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))

When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.

Am I missing something here or is it like that? Any advice will be highly appreciated.

Im filling it in runtime using a procedure.

Private Sub filldisProfiles()
    Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
    Dim tempTb As DataTable
    Dim myTbClass As myClassTableActivities = New myClassTableActivities()
    tempTb = myTbClass.myFunctionFetchTbData(sqlString)

    cmbDisProfile.DataSource = tempTb
    cmbDisProfile.DisplayMember = "discount_profile"
End Sub

Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.

My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.

Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)

        Return fetchedDataTable

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function

' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)

    Dim SqlCmd As New SqlCommand(sqlString, conn)
    Dim dataAdapter As New SqlDataAdapter(SqlCmd)
    Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
    dataAdapter.Update(tbToUpdate)

End Sub

Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
    Try
        Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"

        'Dim searchString As String = txtCategoryCode.Text
        '        searchOwnerCmd.Parameters.Clear()
        '        searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")

        Dim tempTb As DataTable
        Dim myTbClass As myClassTableActivities = New myClassTableActivities()
        tempTb = myTbClass.myFunctionFetchTbData(searchSql)

        If tempTb.Rows.Count = 0 Then
            Return False
        Else
            Return True
        End If

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)

        Return fetchedSearchTB

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function

回答1:


OK. If I understood correctly, you have a problem in retrieving Data [String] from a Database Table into a ComboBox of DropDownStyle [DropDownList].

How do you fill/populate your ComboBox with Data From Database Table ?

In this link, Microsoft docs state, that:

Use the SelectedIndex property to programmatically determine the index of the item selected by the user from the DropDownList control. The index can then be used to retrieve the selected item from the Items collection of the control.

In much more plain English You can never SET ComboBox.Text Value while in DropDownList by code, which you already knew by testing your code, but you need to use DisplayMember and ValueMember or SelectedIndex.

ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))

Please consider populating your ComboBox Control from Database Table using (Key,Value) Dictionary collection, here is an example




回答2:


Thank you guys for all the advice's. The only way it can be done is the way u said. I thought of putting the working code and some points for the benefit of all.

proposed,

  • ComboBox1.SelectedIndex = comboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))"

does not work when u bind the datatable to the combobox. The values should be added to the combo box in run time if the above "SelectedIndex" method to work. The code to add items to the combobox is as follows(myClassTableActivities is a class defined by myself and its shown above),

Private Sub filldisProfiles()
    Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
    Dim tempTb As DataTable
    Dim myTbClass As myClassTableActivities = New myClassTableActivities()
    tempTb = myTbClass.myFunctionFetchTbData(sqlString)

    Dim i As Integer = 0
    For i = 0 To tempTb.Rows.Count - 1
        cmbDisProfile.Items.Add(Trim(tempTb.Rows(i).Item("discount_profile")))
    Next
End Sub

After adding we can use the following code to display the data on combobox (DropDownList).

Private Sub txtItCode_TextChanged(sender As Object, e As EventArgs) Handles txtItCode.TextChanged
    Try
        Dim sqlString As String = "SELECT * FROM tb_items where it_code='" & Trim(txtItCode.Text) & "'"
        Dim tempTb As DataTable
        Dim myTbClass As myClassTableActivities = New myClassTableActivities()
        tempTb = myTbClass.myFunctionFetchTbData(sqlString)

        If Len(txtItCode.Text) < 4 Then
            cmdAdd.Enabled = False
            cmdDelete.Enabled = False
            cmdSave.Enabled = False
        Else
            If tempTb.Rows.Count > 0 Then


                With tempTb
                    txtItName.Text = Trim(tempTb.Rows(0).Item("it_name"))
                    cmbDisProfile.SelectedIndex = cmbDisProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
                    cmbProfitProfile.SelectedIndex = cmbProfitProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_profit_profile")))
                    cmbItCategory.SelectedIndex = cmbItCategory.FindStringExact(Trim(tempTb.Rows(0).Item("it_category")))
                    cmbFinanCategory.SelectedIndex = cmbFinanCategory.FindStringExact((tempTb.Rows(0).Item("it_finance_category")))
                End With
                cmdAdd.Enabled = False
                cmdDelete.Enabled = True
                cmdSave.Enabled = True
            Else
                cmdAdd.Enabled = True
                cmdDelete.Enabled = False
                cmdSave.Enabled = False
                txtItName.Text = ""
                Call fillItCategories()
                Call fillProProfile()
                Call filldisProfiles()
                Call fillFinCat()
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try


来源:https://stackoverflow.com/questions/62120143/cant-display-data-in-combobox-control-of-dropdownstyle-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!