Windows Develop Bookmark and Share   
 index > Windows Forms General > Need help with a ListBox... SelectedIndex = -1 not working properly. Maybe i'm hallucinating.
 

Need help with a ListBox... SelectedIndex = -1 not working properly. Maybe i'm hallucinating.

I instanciate a dialog box like this, from my main form:

/// <summary>
/// Loads up the Brands Dialog Box
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lnkBrand_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
using (dlgBrand _dlg = new dlgBrand())
{
_dlg.ShowDialog();
}
}

Then I have in my little dialog, a  dropdownlist and some textboxes, and when you select an item it puts the info into the textboxes. Or you can add a new item to the ListBox by hitting the "Clear" button at the bottom and entering the info into the textboxes adn hitting submit. Real simple stuff.

Well, when I hit clear and call lbBrands.SelectedIndex = -1 , it selects item 0 in the list.

The ListBox is databound.

Here is the code:

/// <summary>
/// Clears the Form of current Selection
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClear_Click(object sender, System.EventArgs e)
{
//Set Defaults
this.lbBrands.SelectedIndex = -1;
this.txtBrandName.Text = "";
this.SelectedBrandID = 0;
this.SelectedBrandName = "";
}

Here is my databanding of the listbox:

private void lbBrands_SelectedIndexChanged(object sender, System.EventArgs e)
{
if ( ((ListBox)sender).SelectedIndex > -1)
{

this.SelectedBrandID = Convert.ToInt32(lbBrands.SelectedValue);
this.SelectedBrandName = lbBrands.Text;
txtBrandName.Text =
this.SelectedBrandName;

}

}

remedy  Tuesday, August 30, 2005 9:32 PM

It doesn't look as though your code is that which you'd expect to see in a databinding situation. 

In this case the each of the controls would be bound to a common BindingSource.

It looks as though you have a Listbox populated with some items and if you change the listbox item then a textbox is populated and a couple of properties.

Although its VB.NET code its mimicing what you are doing and works just fine.  Instead of selecting a selectedIndex of -1 I set the selectedItems property to nothing.   Ensure that multiselect property is set to false as you only want to be able to select a single item on the listbox.

Public Class Form2
    Private sBrandName As String

    Public Property BrandName() As String
        Get
            Return sBrandName
        End Get
        Set(ByVal value As String)
            sBrandName = value
        End Set
    End Property

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListBox1.SelectedItem = Nothing
        BrandName = Nothing
        Me.TextBox1.Text = ""

    End Sub

    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        If ListBox1.SelectedItem IsNot Nothing Then
            Me.TextBox1.Text = Me.ListBox1.SelectedItem.ToString
            BrandName = Me.ListBox1.SelectedItem.ToString
        End If

    End Sub

    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.ListBox1.Items.Clear()
        Me.ListBox1.Items.Add("Fred")
        Me.ListBox1.Items.Add("John")
        Me.ListBox1.Items.Add("Bill")
        Me.ListBox1.Items.Add("Tony")

    End Sub
End Class

 

 

 

If your using databinding - you probably dont need to set the txtBrandName.text property in the selectedIndexChanged event - you can simply attach the datasource/datamember properties of this textbox control to the same data BindingSource as the listbox.

 

 

spotty  Tuesday, August 30, 2005 11:27 PM
What is occuring is that I am binding a listbox from the database so the person can select a brand name to update or to add a new one to the list (which is really just adding a new one to the database). The dialog is used to both update a brand name and also add a new one, so the clear button removes the selection from the list and also clears the textbox out.

I mistyped what I wrote above. I meant to put in my databinding method not the event for the listbox selected index changed.

My databinding for the listbox is:

private void BindBrandList()
{
   DataTable _dtBrands = AAMP.DataObjects.ProductBrand.List();
   //Check and see if DataTable has rows and bind to ComboBox 
   if (_dtBrands.Rows.Count > 0) 
      {
         this.lbBrands.ValueMember = "id";
         this.lbBrands.DisplayMember = "brand_name";
         this.lbBrands.DataSource = _dtBrands;
      } 
      else 
      {
         this.lbBrands.Items.Add("No Brands Found");
         this.lbBrands.Enabled = false;

      }
}


I guess I can try your ListBox.SelectedItem = null type of thing but what is wierd is that when I call the SelectedIndex = -1, instead of just not selecting anything in the list it removes the selection then runs the method AGAIN and selects item 0 in the list. it is really wierd watching it in debug mode because the event literally fires TWICE when calling selectedIndex = -1.

remedy  Wednesday, August 31, 2005 4:04 AM
Tried:

this.lbBrands.SelectedItems = null;

(threw an error saying the property or indexer is read only)

Tried:

this.lbBrands.SelectedItem = null;

Worked, but then still selected the Index 0 in the list instead of not selecting an item at all.

Found an article that is shown below:
(this didnt work for me either)

Selecting nothing by default

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 = -



remedy  Wednesday, August 31, 2005 4:12 AM

You can use google to search for other answers

Custom Search

More Threads

• Please help correct my program crash error!!!
• is there a control to, create/edit/view reports?
• System.AccessViolationException in System.Drawing caused by DataGridView
• How to add a ContextMenuStrip to a ToolStripDropDownButton
• Focus on Panel Contained Controls
• groupbox creation
• Checked List Box File Type Sorting
• Publish in VB2005
• Print custom size paper
• Number Sorting problem in DataGrid