Solved

Adding a value to a combo box

Posted on 2014-04-01
10
396 Views
Last Modified: 2014-04-08
Experts, I am using a class so that I can add a value which is an ID field, to a combo box. This works great for populating the combo box and getting the value of the selected item in the combo box. But i cannot figure out how to set the item in the combo box for example on the form load event I want to set it to a default value.

This is the class I am using.
    'Create the salesPerson class to add both the text
    'to display and the ID as a value to the list item.
    Public Class salesPerson

        Private strDisplay As String
        Private intID As Integer

        Public Sub New(ByVal pDisplay As String, ByVal pID As Integer)
            strDisplay = pDisplay
            intID = pID
        End Sub

        Private ReadOnly Property displayText() As String
            Get
                Return strDisplay
            End Get
        End Property

        Public ReadOnly Property value() As Integer
            Get
                Return intID
            End Get
        End Property

        Public Overrides Function ToString() As String
            Return strDisplay
        End Function

    End Class

Open in new window


This is how I add items to the combo box.
cmbSales.Items.Add(New salesPerson(displayStr, reader.Item("ID")))

Open in new window


This is how I get the selected item in the combo box.
        Dim oSalesPerson As salesPerson = CType(cmbSales.SelectedItem, salesPerson)
        Dim salesPersonID As Integer = oSalesPerson.value

Open in new window

0
Comment
Question by:Basicfarmer
10 Comments
 
LVL 16

Expert Comment

by:Kalpesh Chhatrala
ID: 39971283
did you set ComboBox ValueMember & DisplayMember ?

If not you need to set it first then you can set default value in load event like below

oSalesPerson.SelectedValue = "Your Value Here"
0
 
LVL 24

Expert Comment

by:chaau
ID: 39971299
If you want to select item you need to set SelectedIndex to the index of the item you wish to be a default item. E.g. if you wish the first item to be a default item you would write:
cmbSales.SelectedIndex = 0

Open in new window

(note: SelectedIndex is a Zero Based)
Setting it to -1 will "unselect" any item in the combobox
If you wish to set it to a different index (i.e. to a third item) you need to remember the item when you are adding the items.
Dim i As Integer
' assign the index to the item you want to make a default selected item
i = cmbSales.Items.Add(New salesPerson(displayStr, reader.Item("ID")))
'add more items, but do not overwrite i:
cmbSales.Items.Add(New salesPerson("another item", 2))
cmbSales.Items.Add(New salesPerson("another item 3", 3))
cmbSales.SelectedIndex = i 'select an item with displayStr

Open in new window

0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39971860
You can also use FindString to retrieve the index of the value you want selected by default:
Dim list As New List(Of SalesPerson) From {
    New SalesPerson(1, "John Doe"),
    New SalesPerson(2, "Jane Doe"),
    New SalesPerson(3, "Bob Smith")
}

ComboBox1.DataSource = list
ComboBox1.ValueMember = "ID"
ComboBox1.DisplayMember = "Name"

ComboBox1.SelectedIndex = ComboBox1.FindString("Bob Smith")

Open in new window

0
 

Author Comment

by:Basicfarmer
ID: 39978873
When I need to set the value of the combo box is at a later time if the user comes back to this form. Then I need to set the combo box to show the current user. When the user first selects his name from the combo box, his ID is stored into a database. So if this form is opened again I will retrieve his ID from the database and that is what I need to use to set the combo box with. I will never know the index.
0
 

Author Comment

by:Basicfarmer
ID: 39979004
Here is my last attempt. I created a function to add all of the data to a list that i can use to make the combo box data bound. Based on my reading I needed to do this to use the value member and data member properties. But I still cannot figure out a way to set the combo box to the item I want using the "ID".
    Private Function GetSales() As List(Of salesPerson)

        Dim sales As New List(Of salesPerson)
        Dim strSql As String = "SELECT ID,UserName FROM Sales"
        Dim cmd As New OleDbCommand(strSql, con)
        Dim reader As OleDbDataReader = cmd.ExecuteReader

        If reader.HasRows Then
            While reader.Read
                sales.Add(New salesPerson(reader.Item("UserName"), reader.Item("ID")))
            End While
        End If

        reader.Close()
        cmd.Dispose()

        Return sales

    End Function

     Private FirstRun_Load(sender as Object, e as System.EventArgs) Handles Me.Load
          cmbSales.DataSource = GetSales()
          cmbSales.DataMember = "UserName"
          cmdSales.ValueMember = "ID"
     End Sub

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 39979048
You can simply use the SelectedValue property to select the correct item:
cmbSales.SelectedValue = <whatever_id_you_want_selected>

Open in new window

0
 

Author Comment

by:Basicfarmer
ID: 39979080
Ok, I added a button to the form and in the button click event I added:
cmbSales.selectedValue = 12
When i hit the button my form just dispeared. So i set a break point at that location and found that the code jumps from this statement into the Public Overrides Function of the salesperson class. Then the code just stops and my form is gone.

What am I doing wrong?
    Private frmMain As Main

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click

        If cmbSales.Text = vbNullString Then
            MsgBox("Please select a user from the list.", vbExclamation, "Quote Master")
            Exit Sub
        End If

        Dim oSalesPerson As salesPerson = CType(cmbSales.SelectedItem, salesPerson)
        Dim strSql As String = "INSERT INTO [User] (UserID) VALUES (" & oSalesPerson.value & ")"
        Dim cmd As New OleDbCommand(strSql, con)
        cmd.ExecuteNonQuery()
        cmd.Dispose()

        Dim ProjectExplorer As New ProjectExplorer
        ProjectExplorer.MdiParent = frmMain
        frmMain.Splitter1.Controls.Add(ProjectExplorer)
        ProjectExplorer.Show()

        Me.Close()

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click

        If MsgBox("Are you sure you want to quit without setting up the program?     ", _
                  MsgBoxStyle.Question + MsgBoxStyle.OkCancel, "Verify action") = MsgBoxResult.Cancel Then Exit Sub

        Me.Close()

    End Sub

    Private Function GetSales() As List(Of salesPerson)

        Dim sales As New List(Of salesPerson)
        Dim strSql As String = "SELECT ID,UserName FROM Sales"
        Dim cmd As New OleDbCommand(strSql, con)
        Dim reader As OleDbDataReader = cmd.ExecuteReader

        If reader.HasRows Then
            While reader.Read
                sales.Add(New salesPerson(reader.Item("UserName"), reader.Item("ID")))
            End While
        End If

        reader.Close()
        cmd.Dispose()

        Return sales

    End Function

    Private Sub fillSales()

        Dim strSql As String = "SELECT Sales.ID, Sales.UserName, Sales.Title, Region.RegionName " & _
                               "FROM Sales " & _
                               "INNER JOIN Region ON Sales.RegionID = Region.ID ORDER BY Sales.UserName"

        Dim cmd As New OleDbCommand(strSql, con)
        Dim reader As OleDbDataReader = cmd.ExecuteReader

        While reader.Read

            Dim displayStr As String = reader.Item("UserName").ToString & " - " & _
                                       reader.Item("Title").ToString & " - " & _
                                       reader.Item("RegionName").ToString

            cmbSales.Items.Add(New salesPerson(displayStr, reader.Item("ID")))

        End While

        reader.Close()
        cmd.Dispose()

    End Sub

    Private Sub FirstRun_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        'fillSales()
        cmbSales.DataSource = GetSales()
        cmbSales.DisplayMember = "UserName"
        cmbSales.ValueMember = "ID"

        cmbSales.SelectedValue = 12

    End Sub

    Public Sub New(oForm As Main)

        InitializeComponent()
        frmMain = oForm

    End Sub

    'Create the salesPerson class to add both the text
    'to display and the ID as a value to the list item.
    Public Class salesPerson

        Private strDisplay As String
        Private intID As Integer

        Public Sub New(ByVal pDisplay As String, ByVal pID As Integer)
            strDisplay = pDisplay
            intID = pID
        End Sub

        Private ReadOnly Property displayText() As String
            Get
                Return strDisplay
            End Get
        End Property

        Public ReadOnly Property value() As Integer
            Get
                Return intID
            End Get
        End Property

        Public Overrides Function ToString() As String
            Return strDisplay
        End Function

    End Class

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        cmbSales.SelectedValue = 12

    End Sub

Open in new window

0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 39979413
Try changing

    Private Sub FirstRun_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        'fillSales()
        cmbSales.DataSource = GetSales()
        cmbSales.DisplayMember = "UserName"
        cmbSales.ValueMember = "ID"

        cmbSales.SelectedValue = 12

    End Sub

Open in new window



To


    Private Sub FirstRun_Load(sender As Object, e As System.EventArgs) Handles Me.Load
       If Not Page.IsPostBack Then
        cmbSales.DataSource = GetSales()
        cmbSales.DisplayMember = "UserName"
        cmbSales.ValueMember = "ID"

        cmbSales.SelectedValue = 12
      End If
    End Sub

Open in new window

0
 

Author Comment

by:Basicfarmer
ID: 39979465
Do i need to import a namespace for this? Intellisense does not give me a "Page" or "IsPostBack".
0
 

Author Comment

by:Basicfarmer
ID: 39979505
I changed the way i was filling the combo box. Below is what I did. Now I am able to use"
cmbSales.selectedValue = 12
But why was the previous way I was filling the combo box not working?
    Private Function getSales() As DataTable

        Dim strSql As String = "SELECT Sales.ID, Sales.UserName, Sales.Title, Region.RegionName " & _
                               "FROM Sales " & _
                               "INNER JOIN Region ON Sales.RegionID = Region.ID ORDER BY Sales.UserName"
        Dim da As New OleDbDataAdapter(strSql, con)
        Dim dt As New DataTable

        da.Fill(dt)

        Return dt

        dt.Dispose()
        da.Dispose()

    End Function

    Private Sub FirstRun_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        cmbSales.DataSource = GetSales()
        cmbSales.DisplayMember = "UserName"
        cmbSales.ValueMember = "ID"

    End Sub

Open in new window

0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now