Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


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

Posted on 2011-10-08
Medium Priority
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

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

Author Comment

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

Assisted Solution

CodeCruiser earned 664 total points
ID: 36936107
Then first item is selected automatically. You can change it back to -1
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 15

Assisted Solution

x77 earned 668 total points
ID: 36936164
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


Author Comment

by:Anthony Matovu
ID: 36936171
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

Jacques Bourgeois (James Burger) earned 668 total points
ID: 36936784
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.

Author Comment

by:Anthony Matovu
ID: 36940773
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Kernel Data Recovery is a renowned Data Recovery solution provider which offers wide range of softwares for both enterprise and home users with its cost-effective solutions. Let's have a quick overview of the journey and data recovery tools range he…
Suggested Courses
Course of the Month14 days, 13 hours left to enroll

578 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