Solved

WPF Listbox Selection

Posted on 2011-09-07
15
612 Views
Last Modified: 2013-11-12
I have a WPF application with a listbox.  I click a button,  add several items to the list and then subsequenly click an item, get back the row number and do some other calcs with that number.

For some reason,  when I click the listbox item, it doesn't unselect a previous item and further sometimes highlights several rows in the listbox.

 
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox lb = (ListBox)sender;
            int n = lb.SelectedIndex;

            //some stuff not related to listbox follows
        }

Open in new window

0
Comment
Question by:hbash
  • 8
  • 5
15 Comments
 
LVL 23

Expert Comment

by:wdosanjos
ID: 36498050
Make sure that your listbox has the SelectionMode property set to Single.
0
 
LVL 1

Author Comment

by:hbash
ID: 36498445
It is set to Single.
0
 
LVL 8

Expert Comment

by:jagrut_patel
ID: 36509117
I second wdosanjos.

Can you post XAML to show how ListBox is configured?
0
 
LVL 1

Author Comment

by:hbash
ID: 36527152
Here is the entire page of xaml

<Window x:Class="WpfBOLViewer.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="627" Width="852" Loaded="Window_Loaded" WindowStartupLocation="CenterScreen" WindowStyle="SingleBorderWindow" SizeToContent="Manual">
    <Grid Height="599">

        <TextBox Margin="152,12,12,63" Name="txtResults"  VerticalScrollBarVisibility="Auto" />

        <Button Height="23" HorizontalAlignment="Left" Margin="12,0,0,27" Name="cmdLoad" VerticalAlignment="Bottom" Width="124" Click="cmdLoad_Click">Load</Button>        

        <ListBox HorizontalAlignment="Left" Margin="12,12,0,63" Name="listBox1" Width="125"  SelectionChanged="listBox1_SelectionChanged" SelectionMode="Single" />

    </Grid>
   
</Window>
0
 
LVL 8

Expert Comment

by:jagrut_patel
ID: 36527221
Hmmm. XAML looks ok!

1. Check/post code in "listBox1_SelectionChanged"? I doubt there could some code in execution of SelectionChanged that is selecting a item from the listbox.
2. Try to test in chunks. Like create hard-coded items in the listbox rather than populating it on button click, do not put "listBox1_SelectionChanged" event, and test the behavior. If this works then remove hard-coded listbox items and now populate it on button click and test. If this works too then connect "listBox1_SelectionChanged" event and test.

I don't see any other reason why this should not work!
0
 
LVL 1

Author Comment

by:hbash
ID: 36527274
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox lb = (ListBox)sender;
            int n = lb.SelectedIndex;

            if (n > -1)
            {
            My250Record mr = ListOfProcessed250Records[n];

            string sAcc = string.Empty;
            string sValue = string.Empty;
            string sNameValue = string.Empty;

            sValue = mr.RecType + mr.DateStamp + mr.RecordBody + mr.CRLF;

            foreach (DataGrp_RecordDefs.RecordLayout.RecordColumn rc in currentRecordSchema)
            {
                if (rc.ExcludeRecordFromReport)
                {
                }
                else
                {
                    sNameValue = SubStringFromChars(sValue.ToCharArray(), rc.FieldStart - 1, rc.FieldEnd - 1);
                    sAcc = sAcc + rc.FieldName + ": " + sNameValue + "\r\n";
                }
            }
            this.txtResults.Text = sAcc;
            }

        }
0
 
LVL 8

Expert Comment

by:jagrut_patel
ID: 36527440
That tosses my first doubt away! SelectionChanged look fine too.

Can you try #2? Can you also show how do you populate the listbox?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:hbash
ID: 36530612
       private List<MyListboxItem> m_ListBoxItems;
        private void InitListBox()
        {
            int nCnt = ListOfProcessed250Records.Count();
            string ni = string.Empty;
            My250Record mr = new My250Record();
            MyListboxItem mli = new MyListboxItem();

            listBox1.Items.Clear();

            txtResults.Text = "";
            m_ListBoxItems = new List<MyListboxItem>();
           
            for (int nlp = 0; nlp < nCnt; nlp++)
            {
                mr = ListOfProcessed250Records[nlp];

               //************************************************************************
                listBox1.Items.Add(mr.EMP_SSN + " : " + mr.RecType);
               //************************************************************************

                mli.Value = mr.EMP_SSN + " : " + mr.RecType;
                m_ListBoxItems.Add(mli);

                mr = new My250Record();
                mli = new MyListboxItem();
            }

            this.Title = "Main Window (" + Convert.ToString(nCnt) + " translactions loaded)";

        }
0
 
LVL 8

Expert Comment

by:jagrut_patel
ID: 36533933
I am curious to see your running application. There does not seem to be anything apparent that can cause such behavior. Code that populates ListBox
as well as SelectionChanged are straightforward.

I think only idea I have left with is to debug and verify whether SelectionMode property is not changed at run-time. You can set-up a break-point in
"listBox1_SelectionChanged" event handler and check the value of this property at run-time.

If this still does not give any clues then I throw in the towel!


0
 
LVL 1

Author Comment

by:hbash
ID: 36538225
I ran with breakpoint in the SelectionChanged event.  The mode of the listbox is still single.  Do we have a bug in WPF here?  What I am doing is really simple stuff.
0
 
LVL 1

Author Comment

by:hbash
ID: 36538645
0
 
LVL 1

Author Comment

by:hbash
ID: 36538679
This "fix" worked.  It appears that there are some optimizations with string storage in .NET and this is the side effect.  The solution requires you wrap the strings in a simple class so that they are handled uniquely.  

Interesting,  but should be something you can turn on/off.
0
 
LVL 8

Accepted Solution

by:
jagrut_patel earned 500 total points
ID: 36540700
Interesting! Thank you for sharing it.
0
 
LVL 1

Author Closing Comment

by:hbash
ID: 36540729
A collaborative effort.  Finally found the solution
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

With most software applications trying to cater to multiple user needs nowadays, the focus is to make them as configurable as possible. For e.g., when creating Silverlight applications which will connect to WCF services, the service end point usuall…
What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), 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…

707 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

15 Experts available now in Live!

Get 1:1 Help Now