why is my the selectedindex of a combobox automatically starts at zero

Posted on 2011-10-08
Last Modified: 2012-05-12
my code is below

       If s = "ALL" Then
            pstr = "select * from [villageUnit];"
            pstr = "select * from [villageUnit] where [country] = '" & s & "';"
        End If
        Dim dbadp As New OleDb.OleDbDataAdapter(pstr, db)
        Dim dTable As New DataTable

        vunits.DataSource = dTable
        vunits.DisplayMember = "villageName"
        vunits.ValueMember = "vid"
Question by:Anthony Matovu
    LVL 83

    Expert Comment

    Indices are 0 based in .NET so first item is at index 0. Selected index will be -1 if no item is selected.
    LVL 1

    Author Comment

    by:Anthony Matovu
    it changes from -1 to 0 when it reads this row
    vunits.DataSource = dTable
    LVL 83

    Assisted Solution

    Then first item is selected automatically. You can change it back to -1
    LVL 15

    Assisted Solution

    I don´t like DataBinding ComboBox behaviour.

    When I initialize a ComboBox, I Set  Me.ComboBox1.SelectedItem = Nothing  or Me.ComboBox1.SelectedIndex = -1.

    But any Change on DataTable (any Row add) can change the combobox.selectedindex:
    Public Class Form1
    Private dt As New DataTable
    Sub New()
        ' Llamada necesaria para el Diseñador de Windows Forms.
        ' Agregue cualquier inicialización después de la llamada a InitializeComponent().
        dt = New DataTable
        Me.ComboBox1.Sorted = True
        Me.ComboBox1.DataSource = dt
        Me.ComboBox1.ValueMember = "x"
        Me.ComboBox1.SelectedItem = Nothing
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End Sub

    Open in new window

    LVL 1

    Author Comment

    by:Anthony Matovu
    I have found this from the net and seem to be very close to what i want. i trying to understand the solution provided

    In a non-databound combo box, nothing is selected unless you explicitly set the SelectedIndex or SelectedItem property. However, when you use data binding, the default behaviour is for the first item to be selected. It can be very difficult trying to figure out how to select nothing. Setting the SelectedItem to null has no effect visually. Setting the SelectedIndex to -1 can cause unpredictable behaviour if the form is an MDI child, or if it is on a tab control and you flip between the tab pages.

    The solution to both problems is to give the combo box a different binding context to the form and tab control, bind the data, and then set the SelectedIndex to -1. Like so:

    [C# .NET] this.companyComboBox.BindingContext = new BindingContext(); // Bind the data this.companyComboBox.SelectedIndex = -
    LVL 40

    Accepted Solution

    DataBinding has its advantages, but also often takes care of too many things and prevent you from working the way you want. Same as x77, I would rather work just a little bit more and not use DataBinding.

    When I am in a rush however, or with simple static lists, I do not suffer the drawbacks of DataBinding and will use it. Here is why the SelectedIndex behaves as it does, and a simple solution.

    SelectedIndex is an Integer. Integer is a structure (not a class), also called a value object. As is the case with all the value objects, it always a value, so it cannot be null. Only reference objects, those based on a class, can be set to Null.

    The default value for numeric structures is 0, so SelectedItem is 0 by default. When you set it to Null, it simply reset it to its default value.

    Personally, I solve a problem such as yours by making sure that the first item in the ComboBox, is a prompt such as <Select a state>. The brackets insure that it will show at the top when displayed alphabetically. That becames my "no selection" entry and I build the logic of my application to disregard that value when it is seleced.
    LVL 1

    Author Comment

    by:Anthony Matovu
    Thank you JameBurger

    Now I have a challenge like below

    This is the code for updating the combobox (smonth) for month.

            smonth.Items.Add((New cValue(" ", 0)))
            smonth.Items.Add((New cValue("January", 1)))
            smonth.Items.Add((New cValue("February", 2)))
            smonth.Items.Add((New cValue("March", 3)))

    It is fine to read the selected value and I can save properly

    Challenge comes when i try to read the saved value from the database and display its test on the combobox. The code below is what i use to display

     If drd(g).ToString.Trim.Length > 0 Then CType(frm.Controls(drd.GetName(g)), ComboBox).SelectedValue = CType(drd(g), Long)


    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
    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…
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

    729 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