Solved

Dynamically loaded items in combobox

Posted on 2004-08-23
17
1,207 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
  • 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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
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

ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Error in script 11 56
C#  Radio button search for Date not DateTime 4 46
Close form "before" open 3 40
compare between entities in entity framework 8 72
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

773 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