473,654 Members | 3,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SelectedIndexCh anged causes selectedindex to reset to -1?

Hi,

I have a couple of win forms where I am editing values that are stored in a
SQL database.

I'm using the listbox control to hold the data object each form interacts
with. Each object is defined by my own classes.

On the first form, I use an approach to reduce the number of database calls.
This essentially consists of :

1. Update the values in the database
2. Update the copy of the object currently being edited with the new values
so that is matches the values saved to the db
3. Re-insert the updated object back into the listbox at the same position.

Step 3 is achieved very simply by the following code:
Me.lbCampaigns. Items.Item(Me.C urrentCampaign. ListPos) = Me.CurrentCampa ign

(The ListPos is an integer property of the object class that is set when the
item is selected from the listbox.)

The re-insertion of the object to the listbox causes the
SelectedIndexCh anged event to fire (although strictly speaking we have not
moved the selection index). In my case, I handle this event and make a call
to refresh the visual control values with the updated object (this is a bit
redundant as we are not moving between selected items, but I can't prevent
the event firing). The SelectedIndex remains at the original value as per
the users selection.

Ok, so this all seems to work fine.

So, I wanted to use the same process on the second form. I implemented
another class to match the requirements of this form. This class also has a
ListPos property defined to store the SelectedIndex value.

In the same manner as on the first form, I copied the updated object
instance back into the listbox.
Me.lbQModes.Ite ms.Item(Me.Curr entQMode.ListPo s) = Me.CurrentQMode

However, for some reason, as soon as the SelectedIndexCh anged event begins,
the SelectedIndex value is reset to -1, which then prevents the subsequent
procedures from being able to operate properly as they rely on being able to
identify and use a selected item.

I can find no obvious or sensible reason for why this second form should
cause a different behaviour in the SelectedIndexCh anged event, so I have
resorted to making a second database call in order to totally reload the
listbox control, then loop through to find the matching ID of the item
selected and re-selecting it.

This approach seems heavy-handed to me and is especially frustrating given
that it works correctly on the first form. I have checked all properties of
the two different listboxes to see if this might have been a possible cause,
but other than name, anchor, position and size, they are using identical
property settings.

I'm at a loss to explain it - can anyone perhaps indicate where I might be
missing something? Not urgent - as I say I've used a total refresh approach
to get past it, but I would prefer the more elegant solution to work!

Thanks.
Oct 3 '06 #1
3 2624
First of all, you have to understand what happens when the selection in a
ListBox, (or various other controls), happens.

If you have no item selected and select an item, the SelectedIndexCh anged
fires once.

If you have an item already selected and select another item, the
SelectedIndexCh anged fires twice. The first time as the current item becomes
deselected and the SelectedIndex becomes -1 and the second time as the new
item becomes selected. This is easily handled by testing for SelectedIndex
= -1 or SelectedItem IsNothing in the SelectedIndexCh anged event handler.

Using the ListBox, as you are, as a container for a collection of your
Campaign objects is perfectly fine but you have to remember that the that
the ListItem does not contain a Campaign object, rather it contains a
reference to your Campaign object.

Because of this there is no need to 'reinsert', as you call it, when you
update one or more properties of the Campaign object. This can easily be
confirmed by:

CurrentCampaign = CType(lbCampaig ns.SelectedItem , Campaign)

CurrentCampaign .ListPos = 12345

Console.WriteLi ne(CType(lbCamp aigns.SelectedI tem,
Campaign).ListP os.ToString())

The result should be 12345 and demonstrates that CurrentCampaign and
lbCampaigns.Sel ectedItem both hold references to the same object without any
need to 'reinsert'.

The act of 'reinsert'ing destroys the current reference and replaces it with
a new reference to the same object. The destruction of it's current
reference is what causes the SelectedIndex to change and whether one thinks
it is intuitive or not, if you think about it, it is actually logical.

"Alec MacLean" <al**********@N O-SPAM-copeohs.comwrot e in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Hi,

I have a couple of win forms where I am editing values that are stored in
a SQL database.

I'm using the listbox control to hold the data object each form interacts
with. Each object is defined by my own classes.

On the first form, I use an approach to reduce the number of database
calls. This essentially consists of :

1. Update the values in the database
2. Update the copy of the object currently being edited with the new
values so that is matches the values saved to the db
3. Re-insert the updated object back into the listbox at the same
position.

Step 3 is achieved very simply by the following code:
Me.lbCampaigns. Items.Item(Me.C urrentCampaign. ListPos) = Me.CurrentCampa ign

(The ListPos is an integer property of the object class that is set when
the item is selected from the listbox.)

The re-insertion of the object to the listbox causes the
SelectedIndexCh anged event to fire (although strictly speaking we have not
moved the selection index). In my case, I handle this event and make a
call to refresh the visual control values with the updated object (this is
a bit redundant as we are not moving between selected items, but I can't
prevent the event firing). The SelectedIndex remains at the original
value as per the users selection.

Ok, so this all seems to work fine.

So, I wanted to use the same process on the second form. I implemented
another class to match the requirements of this form. This class also has
a ListPos property defined to store the SelectedIndex value.

In the same manner as on the first form, I copied the updated object
instance back into the listbox.
Me.lbQModes.Ite ms.Item(Me.Curr entQMode.ListPo s) = Me.CurrentQMode

However, for some reason, as soon as the SelectedIndexCh anged event
begins, the SelectedIndex value is reset to -1, which then prevents the
subsequent procedures from being able to operate properly as they rely on
being able to identify and use a selected item.

I can find no obvious or sensible reason for why this second form should
cause a different behaviour in the SelectedIndexCh anged event, so I have
resorted to making a second database call in order to totally reload the
listbox control, then loop through to find the matching ID of the item
selected and re-selecting it.

This approach seems heavy-handed to me and is especially frustrating given
that it works correctly on the first form. I have checked all properties
of the two different listboxes to see if this might have been a possible
cause, but other than name, anchor, position and size, they are using
identical property settings.

I'm at a loss to explain it - can anyone perhaps indicate where I might be
missing something? Not urgent - as I say I've used a total refresh
approach to get past it, but I would prefer the more elegant solution to
work!

Thanks.

Oct 4 '06 #2
Thanks Stephany,

A very nice explanation - I get it now!

Regards,

Al

"Stephany Young" <noone@localhos twrote in message
news:eJ******** ******@TK2MSFTN GP06.phx.gbl...
First of all, you have to understand what happens when the selection in a
ListBox, (or various other controls), happens.

If you have no item selected and select an item, the SelectedIndexCh anged
fires once.

If you have an item already selected and select another item, the
SelectedIndexCh anged fires twice. The first time as the current item
becomes deselected and the SelectedIndex becomes -1 and the second time as
the new item becomes selected. This is easily handled by testing for
SelectedIndex = -1 or SelectedItem IsNothing in the SelectedIndexCh anged
event handler.

Using the ListBox, as you are, as a container for a collection of your
Campaign objects is perfectly fine but you have to remember that the that
the ListItem does not contain a Campaign object, rather it contains a
reference to your Campaign object.

Because of this there is no need to 'reinsert', as you call it, when you
update one or more properties of the Campaign object. This can easily be
confirmed by:

CurrentCampaign = CType(lbCampaig ns.SelectedItem , Campaign)

CurrentCampaign .ListPos = 12345

Console.WriteLi ne(CType(lbCamp aigns.SelectedI tem,
Campaign).ListP os.ToString())

The result should be 12345 and demonstrates that CurrentCampaign and
lbCampaigns.Sel ectedItem both hold references to the same object without
any need to 'reinsert'.

The act of 'reinsert'ing destroys the current reference and replaces it
with a new reference to the same object. The destruction of it's current
reference is what causes the SelectedIndex to change and whether one
thinks it is intuitive or not, if you think about it, it is actually
logical.

"Alec MacLean" <al**********@N O-SPAM-copeohs.comwrot e in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>Hi,

I have a couple of win forms where I am editing values that are stored in
a SQL database.

I'm using the listbox control to hold the data object each form interacts
with. Each object is defined by my own classes.

On the first form, I use an approach to reduce the number of database
calls. This essentially consists of :

1. Update the values in the database
2. Update the copy of the object currently being edited with the new
values so that is matches the values saved to the db
3. Re-insert the updated object back into the listbox at the same
position.

Step 3 is achieved very simply by the following code:
Me.lbCampaigns .Items.Item(Me. CurrentCampaign .ListPos) =
Me.CurrentCamp aign

(The ListPos is an integer property of the object class that is set when
the item is selected from the listbox.)

The re-insertion of the object to the listbox causes the
SelectedIndexC hanged event to fire (although strictly speaking we have
not moved the selection index). In my case, I handle this event and make
a call to refresh the visual control values with the updated object (this
is a bit redundant as we are not moving between selected items, but I
can't prevent the event firing). The SelectedIndex remains at the
original value as per the users selection.

Ok, so this all seems to work fine.

So, I wanted to use the same process on the second form. I implemented
another class to match the requirements of this form. This class also
has a ListPos property defined to store the SelectedIndex value.

In the same manner as on the first form, I copied the updated object
instance back into the listbox.
Me.lbQModes.It ems.Item(Me.Cur rentQMode.ListP os) = Me.CurrentQMode

However, for some reason, as soon as the SelectedIndexCh anged event
begins, the SelectedIndex value is reset to -1, which then prevents the
subsequent procedures from being able to operate properly as they rely on
being able to identify and use a selected item.

I can find no obvious or sensible reason for why this second form should
cause a different behaviour in the SelectedIndexCh anged event, so I have
resorted to making a second database call in order to totally reload the
listbox control, then loop through to find the matching ID of the item
selected and re-selecting it.

This approach seems heavy-handed to me and is especially frustrating
given that it works correctly on the first form. I have checked all
properties of the two different listboxes to see if this might have been
a possible cause, but other than name, anchor, position and size, they
are using identical property settings.

I'm at a loss to explain it - can anyone perhaps indicate where I might
be missing something? Not urgent - as I say I've used a total refresh
approach to get past it, but I would prefer the more elegant solution to
work!

Thanks.


Oct 4 '06 #3
You can do a "RemoveHand ler" then do your stuff then a "AddHandler ". This
will prevent the events from firing while you do your thing.
--
Dennis in Houston
"Alec MacLean" wrote:
Thanks Stephany,

A very nice explanation - I get it now!

Regards,

Al

"Stephany Young" <noone@localhos twrote in message
news:eJ******** ******@TK2MSFTN GP06.phx.gbl...
First of all, you have to understand what happens when the selection in a
ListBox, (or various other controls), happens.

If you have no item selected and select an item, the SelectedIndexCh anged
fires once.

If you have an item already selected and select another item, the
SelectedIndexCh anged fires twice. The first time as the current item
becomes deselected and the SelectedIndex becomes -1 and the second time as
the new item becomes selected. This is easily handled by testing for
SelectedIndex = -1 or SelectedItem IsNothing in the SelectedIndexCh anged
event handler.

Using the ListBox, as you are, as a container for a collection of your
Campaign objects is perfectly fine but you have to remember that the that
the ListItem does not contain a Campaign object, rather it contains a
reference to your Campaign object.

Because of this there is no need to 'reinsert', as you call it, when you
update one or more properties of the Campaign object. This can easily be
confirmed by:

CurrentCampaign = CType(lbCampaig ns.SelectedItem , Campaign)

CurrentCampaign .ListPos = 12345

Console.WriteLi ne(CType(lbCamp aigns.SelectedI tem,
Campaign).ListP os.ToString())

The result should be 12345 and demonstrates that CurrentCampaign and
lbCampaigns.Sel ectedItem both hold references to the same object without
any need to 'reinsert'.

The act of 'reinsert'ing destroys the current reference and replaces it
with a new reference to the same object. The destruction of it's current
reference is what causes the SelectedIndex to change and whether one
thinks it is intuitive or not, if you think about it, it is actually
logical.

"Alec MacLean" <al**********@N O-SPAM-copeohs.comwrot e in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Hi,

I have a couple of win forms where I am editing values that are stored in
a SQL database.

I'm using the listbox control to hold the data object each form interacts
with. Each object is defined by my own classes.

On the first form, I use an approach to reduce the number of database
calls. This essentially consists of :

1. Update the values in the database
2. Update the copy of the object currently being edited with the new
values so that is matches the values saved to the db
3. Re-insert the updated object back into the listbox at the same
position.

Step 3 is achieved very simply by the following code:
Me.lbCampaigns. Items.Item(Me.C urrentCampaign. ListPos) =
Me.CurrentCampa ign

(The ListPos is an integer property of the object class that is set when
the item is selected from the listbox.)

The re-insertion of the object to the listbox causes the
SelectedIndexCh anged event to fire (although strictly speaking we have
not moved the selection index). In my case, I handle this event and make
a call to refresh the visual control values with the updated object (this
is a bit redundant as we are not moving between selected items, but I
can't prevent the event firing). The SelectedIndex remains at the
original value as per the users selection.

Ok, so this all seems to work fine.

So, I wanted to use the same process on the second form. I implemented
another class to match the requirements of this form. This class also
has a ListPos property defined to store the SelectedIndex value.

In the same manner as on the first form, I copied the updated object
instance back into the listbox.
Me.lbQModes.Ite ms.Item(Me.Curr entQMode.ListPo s) = Me.CurrentQMode

However, for some reason, as soon as the SelectedIndexCh anged event
begins, the SelectedIndex value is reset to -1, which then prevents the
subsequent procedures from being able to operate properly as they rely on
being able to identify and use a selected item.

I can find no obvious or sensible reason for why this second form should
cause a different behaviour in the SelectedIndexCh anged event, so I have
resorted to making a second database call in order to totally reload the
listbox control, then loop through to find the matching ID of the item
selected and re-selecting it.

This approach seems heavy-handed to me and is especially frustrating
given that it works correctly on the first form. I have checked all
properties of the two different listboxes to see if this might have been
a possible cause, but other than name, anchor, position and size, they
are using identical property settings.

I'm at a loss to explain it - can anyone perhaps indicate where I might
be missing something? Not urgent - as I say I've used a total refresh
approach to get past it, but I would prefer the more elegant solution to
work!

Thanks.


Oct 5 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
8383
by: Edward | last post by:
I am having a terrible time getting anything useful out of a listbox on my web form. I am populating it with the results from Postcode lookup software, and it is showing the results fine. What I want to do is to allow the user to click on the row that corresponds to the correct address, and have the code behind populate the form's Address1, Address2 etc. controls with the relevant data items. I put the code for this into the...
9
3021
by: Steve Wolfie | last post by:
Hi! I am *still* developing an asp.net app that i would like to do the following: i want a user to select a category from a drop down. if they select the last option "other" then i would like to dynamically display a textbox that i have initially set the visible attribute to "false" i use the code as follows:
7
8790
by: sparkle | last post by:
Hi Everybody, I'm filling a combobox from a class, which works fine on it's own. But when I insert code to fill in other controls something in the combobox fill is causing the SelectedIndexChanged event to happen when the form (hence combobox) loads, not when I select something from the combobox. Do I have something in the wrong order? I've read that that sometimes
2
3675
by: blue_nirvana | last post by:
I use a AddHandler statement in the load event of a form to assoicate a routine with a combobox. When I populate the form, I select the approiate value from the combobox by using combobox.selectedvalue = value. The weird thing is sometimes this causes the assoicated routine to be called and sometimes it does not. The combobox below it that is completely identical except for the name works every time. After the form is displayed, you can...
3
2830
by: martin1 | last post by:
Hi, All, I want user select first item (called All) in listbox, then all other items are selected by SetSelected method, but in loop (see code below) whenever going to SetSelected(), the SelectedIndexChanged event keep fire and loop doesn't go to next, finally the program stop at infinite loop. Sub lstCem_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstCem.SelectedIndexChanged If...
6
10809
by: tbrown | last post by:
I have a combobox with items like this: {one,two,three}. The selected index is 0, so "one" appears in the combobox text. When the user drops down the list, and selects "two", for example, I modify the Items collection to be {two,one,three} and now want "two" to appear in the combobox text. However, the combobox text is now blank. the is apparently somehow the result of having changed the combobox.Items collection. If, trying to fix...
4
5247
by: lakepeir | last post by:
Hello, I have combobox with a selectedindexchanged method that seems to be called when starting the application, launching the form with the combobox and making a change in the drop down box of the combobox. Can anyone tell me why the method is called so often? I would only like the method executed when a user makes a change in the drop down box. Am I using the incorrect method. Thanks.
5
2181
by: revbart | last post by:
Yep, that's me. I'll bet I've read a hundred articles somewhere or another, but I just can't get the thing to work. I'm working on a custom solution. One of the major UIs includes a calendar-style presentation. The navigation controls at the top of the calendar include four LinkButton controls (prevYear, prevMonth, nextMonth, nextYear) and two DropDownList controls (monthSelector, yearSelector). The DropDownList webcontrols are set with...
2
2954
by: tshad | last post by:
In my VS 2003 Windows Forms page, when I initially fill my ComboBox (SystemList), it goes to the SelectedIndexChanged event which calls the Loademails() function. I then call it again in the Form1Load function. How do I get it not to call it in the SelectedIndexChanged from the Form1Load function? Normally, I want it to call it but not when I initally fill the ComboBox. *********************************************************...
0
8376
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8290
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8489
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8594
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7307
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5622
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4149
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1596
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.