Solved

Dynamically loaded items in combobox

Posted on 2004-08-23
17
1,209 Views
Last Modified: 2012-06-21
hello experts,
i've got a problem using a combobox that should display dynamically loaded items. till now i only worked with comboboxes that items were loaded once at startup. i used the datasource-property that i linked to an IList consisting of objects. these objects had the following structure:

string Object.Display - the value that should be displayed by combobox
string Object.Value   - the key in the back to be used for further processing

i mapped the Display-property to comboboxes Displaymember-property and Value-property to Valuemember. Nice thing - did it well. But it does not work if you want to change the items of the combobox while working with it.

I remember having encountered the problem with listboxes, too. there i solved it forgetting the DataSource-property and using the old-style Items-property. Via the Items.Add-method i added all my items, via Items.Clear the collection was emptied to be filled with new data. That works well with Listboxes. But it seems not to be working with comboboxes?

does anyone of you know a nice solution to this problem?

thanks in advance.
0
Comment
Question by:kolpdc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 4
  • 2
  • +1
17 Comments
 
LVL 1

Expert Comment

by:hammadraza
ID: 11868801
Can you show some code?
0
 
LVL 4

Expert Comment

by:somnatic
ID: 11868940
obj.Items.Clear();
obj.Items.Add();

works for ComboBoxes just as well ..
of course, no data binding ..
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11868942

        /**
         * Fill a combobox.
         * Fill a combobox by adding the list to the ObjectCollection.
         *
         * @param p_Box combobox to be filled
         * @param p_List list to be filled into combobox
         * @return bool correctly filled?
         */
        private bool fillDynamicComboBox(
            ComboBox p_Box,
            IList          p_List)
        {
            if ((p_Box != null)  &&
                (p_List != null)) {

                p_Box.BeginUpdate();

                p_Box.DisplayMember = "Display";
                p_Box.ValueMember   = "Value";

                p_Box.Items.Clear();
                for(int i=0; i < p_List.Count; i++)
                    p_Box.Items.Add((CAddValue)p_List[i]);

                p_Box.EndUpdate();
            }
            else
                return false;

            return true;
        } //fillDynamicComboBox

        IList list = new ArrayList();
        //Filled with objects that have two public properties string Display, string Value

        fillDynamicComboBox(cboTest, list);
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 4

Author Comment

by:kolpdc
ID: 11868953
this version works fine, if you change the parameter "ComboBox p_Box" to "ListBox p_Box"
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11868974
yes, normally it should work, but for in this case it does not seem to work. the collection is updated, but i am not able to access anything. SelectedValue, SelectedItem is always undefined, SelectedIndex is always -1 although i manually change the combobox's item choosen.

one item added to the Items-collection is a object of type CAddValue. the member-properties are mapped to the objects properties. so normally it should work. but it does not.
0
 
LVL 4

Expert Comment

by:somnatic
ID: 11869002
call

ComboBox.Select() after you call .SelectedValue
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11869074
unfortunately it does not work.

also debugger always shows that SelectedValue is undefined although one step before i gave it a value.
0
 
LVL 4

Expert Comment

by:somnatic
ID: 11869079
can you show the code where the debugger shows you that the value is undefined ?
maybe 10 lines around that ?
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11869161


   //The class used to hold my displaymember and the valuemember (key)
   public class CAddValue
   {
        private string m_Display;
        private string m_Value;
   
        public CAddValue(string Display, string Value) {
            m_Display = Display;
            m_Value = Value;
        }

        public string Display {
            get { return m_Display;  }
            set { m_Display = value; }
        }
        public string Value {
            get{ return m_Value;   }
            set { m_Value = value; }
        }

    } //CAddValue

   //******************************************************

        /*Only example - the static version where the box is only filled once. works well, but is not usable for dynamic reload of items*/
        /**
         * Fill a combobox.
         * Fill a combobox by adding the list to the ObjectCollection.
         *
         * @param p_Box combobox to be filled
         * @param p_List list to be filled into combobox
         * @return bool correctly filled?
         */
        private bool fillStaticCboBox(
            ComboBox p_Box,
            IList    p_List)
        {
            if ((p_Box != null)  &&
                (p_List != null) &&
                (p_Box.DataSource == null)) {

                p_Box.BeginUpdate();
                p_Box.DisplayMember = "Display";
                p_Box.ValueMember   = "Value";
                p_Box.DataSource = p_List;
                p_Box.EndUpdate();
            }
            else
                return false;

            return true;
        } //fillStaticCboBox

   //-----------------------------------------------------

        /* the dynamic version using items-collection. adding and removing elements works well. */
        /**
         * Fill a listbox.
         * Fill a listbox by adding the list to the ObjectCollection.
         *
         * @param p_Box listbox to be filled
         * @param p_List list to be filled into combobox
         * @return bool correctly filled?
         */
        private bool fillDynamicComboBox(
            ComboBox p_Box,
            IList    p_List)
        {
            if ((p_Box != null)  &&
                (p_List != null)) {

                p_Box.BeginUpdate();

                p_Box.DisplayMember = "Display";
                p_Box.ValueMember   = "Value";

                p_Box.Items.Clear();
                for(int i=0; i < p_List.Count; i++)
                    p_Box.Items.Add((CAddValue)p_List[i]);

                p_Box.EndUpdate();
            }
            else
                return false;

            return true;
        } //fillDynamicComboBox

   //-----------------------------------------------------

        /* This method fills CAddValue-objects from database and adds them to an IList*/
        /**
         * Fill list.
         * Fill list from a dblayer-manager.
         *
         * @param p_List list to be filled
         * @param p_Manager dblayer-manager
         */
        private void fillDBLayerList(
            IList                    p_List,
            IDBLayerManager p_Manager)
        {
            p_Manager.loadFromDb();

            p_List.Clear();
            p_List.Add(new CAddValue("", "0"));

            for(int i=0; i < p_Manager.Count(); i++) {
                p_List.Add(
                    new CAddValue(p_Manager.GetObject(i).ToString(), p_Manager.GetObject(i).GetKey().ToString()));
            }
        } //fillDBLayerList

   //-----------------------------------------------------
   //IList is filled
   fillDBLayerList(m_SlPrtnrList, m_CSlPrtnrMngr);

   //Combobox is filled with IList
   fillDynamicComboBox(cboSLPartner, m_SlPrtnrList);

   //-----------------------------------------------------
   //Later one item of the combobox shall be selected
   cboSLPartner.SelectedValue = p_obj.SLPartner.ToString();    //same as cboSLPartner.SelectedValue = "2";
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11869171
that's the whole story.
0
 
LVL 4

Expert Comment

by:somnatic
ID: 11869520
are u sure that your IList p_List is correctly filled ?
does the comboBox show the data lines ?
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11869559
yes. it shows them. and i'm able to select an entry manually. only problem - i'm not able to get its value programmatically after the index changed.
0
 
LVL 4

Accepted Solution

by:
AndreSteffens earned 500 total points
ID: 11881316
Hi there!

After a few hours of nailbiting and hair-out-pulling: I think you need the following code:
      private void btnRemoveEntry_Click(object sender, System.EventArgs e)
      {
            cboTest.SelectedIndex=-1;
            cboTest.DisplayMember=String.Empty;
            cboTest.ValueMember=String.Empty;
            list.RemoveAt(5);//provide any other code to change the underlying datasource
            cboTest.DisplayMember="Display";
            cboTest.ValueMember="Value";
            cboTest.SelectedIndex=-1;
      }
You cannot Add to or Remove from the Items collection once you have set the Datasource. Funnily enough setting the Datasource to null, Clearing and reconnecting the DataSource doesn't work either.
You have to disconnect the Datasource by:
Clearing any selection (SelectedIndex=-1)
Clearing Display and Value Members
THEN change the DataSource (and not a moment before or all kinds of strange behaviour ensues)
set the Display and Value Members back to the properties they were before.
Deselecting again as the the combobox will give the impression that the user has selected an item while in fact the SelectedIndex=-1;
Hope this solves your problem!

André
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11882231
AndreSteffens - great solution! works well! how did you find out?! try and error? i remember having searched for a long time before around a year. great solution - thanks.

(hope that behavior won't change depending on weather, light emission or a butterfly's moving wing...;)
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11882284
for interested readers - here's the code-solution:

        /**
         * Fill a combobox.
         * Fill a combobox by adding the list to the ObjectCollection.
         *
         * @param p_Box combobox to be filled
         * @param p_List list to be filled into combobox
         * @return bool correctly filled?
         */
        private bool fillDynamicComboBox(
            ComboBox p_Box,
            IList    p_List)
        {
            if ((p_Box != null)  &&
                (p_List != null)) {

                p_Box.BeginUpdate();

                //Unlink values (using magic)
                p_Box.SelectedIndex   = -1;
                p_Box.DisplayMember = String.Empty;
                p_Box.ValueMember   = String.Empty;

                //Link values
                p_Box.DataSource      = p_List;
                p_Box.DisplayMember = "Display";
                p_Box.ValueMember   = "Value";
                p_Box.SelectedIndex   = -1;

                p_Box.EndUpdate();
            }
            else
                return false;

            return true;
        } //fillDynamicComboBox
0
 
LVL 4

Expert Comment

by:AndreSteffens
ID: 11882372
Hi kolpc

Thanks for the compliment! Trial and error, or typing and cursing, typing and cursing, and even typing and cursing it was, but eternal bliss ensued! I see that you unlink and link the datasource after you change the datasource. For me that didn't work, I had to unlink first, then change, than link.

Regards,

André
0
 
LVL 4

Author Comment

by:kolpdc
ID: 11889790
it's nice to know that even logically-thinking persons that often live in 0-1-world are able to discover magic somewhen somewhere... ;)

like said - great thing. thanks.
0

Featured Post

Independent Software Vendors: 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

Suggested Solutions

Title # Comments Views Activity
Name Space error VS2015 1 37
C# Service FileSystemwatcher isse 9 47
Coding for the first time 9 70
Updating a single record in forEach using C#/Entity 7 26
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

730 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