Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. Match Two List Box By Sorting ...

Match Two List Box By Sorting ...

Scheduled Pinned Locked Moved C#
algorithmsregexhelpquestion
11 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    nassimnastaran
    wrote on last edited by
    #1

    Hi All ! I have Two List Box , ListBox1 And ListBox2 , there are these Items for e.g.:

    ListBox1[0]-->"City One" ---------------- ListBox2[0]=2500
    ListBox1[1]-->"City Two" ---------------- ListBox2[1]=3000
    ListBox1[2]-->"City Three" ---------------- ListBox2[2]=1500

    I want to Sort ListBox2 , And The same Time all Items In ListBox1 Change (Based on ListBox2) How Can I do it ! Thanks for Any Help Regards !

    N L B D 4 Replies Last reply
    0
    • N nassimnastaran

      Hi All ! I have Two List Box , ListBox1 And ListBox2 , there are these Items for e.g.:

      ListBox1[0]-->"City One" ---------------- ListBox2[0]=2500
      ListBox1[1]-->"City Two" ---------------- ListBox2[1]=3000
      ListBox1[2]-->"City Three" ---------------- ListBox2[2]=1500

      I want to Sort ListBox2 , And The same Time all Items In ListBox1 Change (Based on ListBox2) How Can I do it ! Thanks for Any Help Regards !

      N Offline
      N Offline
      Not Active
      wrote on last edited by
      #2

      Please clarify what you are trying to accomplish. It isn't very clear, at least to me.


      No comment

      1 Reply Last reply
      0
      • N nassimnastaran

        Hi All ! I have Two List Box , ListBox1 And ListBox2 , there are these Items for e.g.:

        ListBox1[0]-->"City One" ---------------- ListBox2[0]=2500
        ListBox1[1]-->"City Two" ---------------- ListBox2[1]=3000
        ListBox1[2]-->"City Three" ---------------- ListBox2[2]=1500

        I want to Sort ListBox2 , And The same Time all Items In ListBox1 Change (Based on ListBox2) How Can I do it ! Thanks for Any Help Regards !

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        The question is not clear. Two hints nevertheless: 1. ListBoxes (anc ComboBoxes) can do much more than hold strings; you can store any kind of object in there, i.e. show some text (maybe their ToString result) but also contain a lot more information, which might define their sorting order. 2. There are all kinds of ways to get a collection sorted; here[^] is an overview I created. :)

        Luc Pattyn [My Articles] Nil Volentibus Arduum

        N 1 Reply Last reply
        0
        • L Luc Pattyn

          The question is not clear. Two hints nevertheless: 1. ListBoxes (anc ComboBoxes) can do much more than hold strings; you can store any kind of object in there, i.e. show some text (maybe their ToString result) but also contain a lot more information, which might define their sorting order. 2. There are all kinds of ways to get a collection sorted; here[^] is an overview I created. :)

          Luc Pattyn [My Articles] Nil Volentibus Arduum

          N Offline
          N Offline
          nassimnastaran
          wrote on last edited by
          #4

          Excuse Me ! See Here :

          ListBox1.Items[0]-->"City One" ---------------- ListBox2.Items[0]=2500
          ListBox1.Items[1]->"City Two" ---------------- ListBox2.Items[1]=3000
          ListBox1.Items[2]-->"City Three" ---------------- ListBox2.Items[2]=1500

          When I sorting ListBox2(by Number) , I want To Change ListBox1 (by the Index of ListBox2) Like these :

          ListBox1.Items[0]->"City Two" <----------------> ListBox2.Items[0]=3000
          ListBox1.Items[1]-->"City One" <----------------> ListBox2.Items[1]=2500
          ListBox1.Items[2]-->"City Three" <----------------> ListBox2.Items[2]=1500

          Thanks

          L 1 Reply Last reply
          0
          • N nassimnastaran

            Excuse Me ! See Here :

            ListBox1.Items[0]-->"City One" ---------------- ListBox2.Items[0]=2500
            ListBox1.Items[1]->"City Two" ---------------- ListBox2.Items[1]=3000
            ListBox1.Items[2]-->"City Three" ---------------- ListBox2.Items[2]=1500

            When I sorting ListBox2(by Number) , I want To Change ListBox1 (by the Index of ListBox2) Like these :

            ListBox1.Items[0]->"City Two" <----------------> ListBox2.Items[0]=3000
            ListBox1.Items[1]-->"City One" <----------------> ListBox2.Items[1]=2500
            ListBox1.Items[2]-->"City Three" <----------------> ListBox2.Items[2]=1500

            Thanks

            L Offline
            L Offline
            Luc Pattyn
            wrote on last edited by
            #5

            If I understand you correctly (you are still only spending one short sentence to "explain" things!), I think you're best approach would be: 1. to have a class City with properties for Name, SomeNumber, and maybe more. 2. have one, not two, collections of such City instances; the collection lives outside any ListBox (as the cities do). A List<City> would do fine as collection here. 3. sort that collection any way you choose. My article explains how. 4. have a ListBox that shows the SomeNumber property of said collection. Databinding could do that for you (set DataSource and DisplayMember, and that is why City needs properties). 5. have another ListBox that shows the Name property of said collection. Databinding again. :)

            Luc Pattyn [My Articles] Nil Volentibus Arduum

            N 1 Reply Last reply
            0
            • L Luc Pattyn

              If I understand you correctly (you are still only spending one short sentence to "explain" things!), I think you're best approach would be: 1. to have a class City with properties for Name, SomeNumber, and maybe more. 2. have one, not two, collections of such City instances; the collection lives outside any ListBox (as the cities do). A List<City> would do fine as collection here. 3. sort that collection any way you choose. My article explains how. 4. have a ListBox that shows the SomeNumber property of said collection. Databinding could do that for you (set DataSource and DisplayMember, and that is why City needs properties). 5. have another ListBox that shows the Name property of said collection. Databinding again. :)

              Luc Pattyn [My Articles] Nil Volentibus Arduum

              N Offline
              N Offline
              nassimnastaran
              wrote on last edited by
              #6

              my English is not Good :doh: my item in ListBox2 is 3 and is Only Number field : as I said :

              ListBox2.Items[0]=2500
              ListBox2.Items[1]=3000
              ListBox2.Items[2]=1500

              Also the Items for ListBox1 is 3 but String Field , Like these as I Said :

              ListBox1.Items[0]-->"City One"
              ListBox1.Items[1]->"City Two"
              ListBox1.Items[2]-->"City Three"

              -------------------------------- in fact my project is about Population , in ListBox1 , we Name of City and in ListBox2 is Their Population :Like these ,

              City One =2500
              City Two=3000
              City Three=1500

              Now When I Want To sort ListBox2 , Also ListBox1 should be Sorted . thanks for your patient Regards!

              L 1 Reply Last reply
              0
              • N nassimnastaran

                my English is not Good :doh: my item in ListBox2 is 3 and is Only Number field : as I said :

                ListBox2.Items[0]=2500
                ListBox2.Items[1]=3000
                ListBox2.Items[2]=1500

                Also the Items for ListBox1 is 3 but String Field , Like these as I Said :

                ListBox1.Items[0]-->"City One"
                ListBox1.Items[1]->"City Two"
                ListBox1.Items[2]-->"City Three"

                -------------------------------- in fact my project is about Population , in ListBox1 , we Name of City and in ListBox2 is Their Population :Like these ,

                City One =2500
                City Two=3000
                City Three=1500

                Now When I Want To sort ListBox2 , Also ListBox1 should be Sorted . thanks for your patient Regards!

                L Offline
                L Offline
                Luc Pattyn
                wrote on last edited by
                #7

                My earlier reply stands. You should not put just strings in a ListBox, if the population numbers were 10000, 3000, and 1000 you would never get them sorted properly using strings. :)

                Luc Pattyn [My Articles] Nil Volentibus Arduum

                N 1 Reply Last reply
                0
                • L Luc Pattyn

                  My earlier reply stands. You should not put just strings in a ListBox, if the population numbers were 10000, 3000, and 1000 you would never get them sorted properly using strings. :)

                  Luc Pattyn [My Articles] Nil Volentibus Arduum

                  N Offline
                  N Offline
                  nassimnastaran
                  wrote on last edited by
                  #8

                  But We have "Two" ListBox, ListBox1 for City And ListBox2 for their Population Regards!

                  1 Reply Last reply
                  0
                  • N nassimnastaran

                    Hi All ! I have Two List Box , ListBox1 And ListBox2 , there are these Items for e.g.:

                    ListBox1[0]-->"City One" ---------------- ListBox2[0]=2500
                    ListBox1[1]-->"City Two" ---------------- ListBox2[1]=3000
                    ListBox1[2]-->"City Three" ---------------- ListBox2[2]=1500

                    I want to Sort ListBox2 , And The same Time all Items In ListBox1 Change (Based on ListBox2) How Can I do it ! Thanks for Any Help Regards !

                    B Offline
                    B Offline
                    BillWoodruff
                    wrote on last edited by
                    #9

                    I interpret your question as: Given two List Boxes: 1. where initially ListBox1 is sorted by some criterion (alpha-numeric ?) 2. where initially each ListBox2 item is associated with the item in ListBox1 with the same index (even though they may "appear" unsorted). Then: 1. in the case where you sort ListBox2 by some criterion 2. you want the items in ListBox1 to remain in matching ordinal position with their "associated" items in ListBox2. What's "missing" from the picture ... but we can "guess" at ... is if you always are going to sort ListBox2 the same way: we assume here that you are not sorting by just setting

                    ListBox2.Sorted = true;

                    Which will give you an alphabetic ascending sort. Your example result shows a sort of ListBox2 in descending order. Since ListBox Items are all strings, there is the question of whether you really want to sort the Items in ListBox2 as strings or as numbers. Solution ? 1. abstract away the data and associations from the ListBoxes: a. I'd do this with a Dictionary<string, int> : why use string as the Key: because it's unlikely you'd have two identical city-names, but, perhaps, very possible, you'd have identical population ? 2. On Form Load, or whatever, populate this Dictionary with the CityName-Population data. 3. Create a function that populates the ListBoxes based on enumerating the Dictionary<string, int> 4. Create a function that sorts the Dictionary by Value (strings) in descending order: Dictionary + Linq will do this for you. Example code:

                    private Dictionary<string, int> PopCityDict;

                    private void Form1_Load(object sender, EventArgs e)
                    {
                    PopCityDict = new Dictionary<string, int>
                    {
                    {"City One", 2500},
                    {"City Two", 3000},
                    {"City Three", 1500}
                    };

                    InitializeListBoxes();
                    

                    }

                    private void InitializeListBoxes()
                    {
                    listBox1.Items.Clear();
                    listBox2.Items.Clear();

                    foreach (var kvp in PopCityDict)
                    {
                        listBox1.Items.Add(kvp.Key);
                        listBox2.Items.Add(kvp.Value);
                    }
                    

                    }

                    private void SortDescendingButton_Click(object sender, EventArgs e)
                    {
                    listBox1.Items.Clear();
                    listBox2.Items.Clear();

                    foreach (var kvp in PopCityDict.OrderByDescending(criterion => criterion.Value))
                    {
                        listBox1.Items.Add(kvp.Key);
                        listBox2.Items.Add(kvp.Value);
                    }
                    

                    }

                    Discussion: The sort will not change the underlying stru

                    1 Reply Last reply
                    0
                    • N nassimnastaran

                      Hi All ! I have Two List Box , ListBox1 And ListBox2 , there are these Items for e.g.:

                      ListBox1[0]-->"City One" ---------------- ListBox2[0]=2500
                      ListBox1[1]-->"City Two" ---------------- ListBox2[1]=3000
                      ListBox1[2]-->"City Three" ---------------- ListBox2[2]=1500

                      I want to Sort ListBox2 , And The same Time all Items In ListBox1 Change (Based on ListBox2) How Can I do it ! Thanks for Any Help Regards !

                      D Offline
                      D Offline
                      DaveyM69
                      wrote on last edited by
                      #10

                      There have been several things suggested but you don't seem to be understanding it, I'll try to help. You seem to be getting confused about how much data you have. You only have ONE collection of cities, you just happen to be showing the individual bits of information (name, population) on two seperate controls. The first thing to do is to get your information into one City class and provide methods for sorting based on name or population - something like:

                      public class City
                      {
                      public const int MinPopulation = 0;

                      public event EventHandler PopulationChanged;
                      
                      private string name;
                      private int population;
                      
                      public City(string name, int population)
                      {
                          if (string.IsNullOrEmpty(name))
                              throw new ArgumentNullException("name", "Name cannot be null or empty");
                          // Do more validation here for only whitespace etc
                      
                          if (population < MinPopulation)
                              throw new ArgumentOutOfRangeException(
                                  "population",
                                  string.Format("Population cannot be less than {0}", MinPopulation));
                          this.name = name;
                          this.population = population;
                      }
                      
                      public string Name
                      {
                          get { return name; }
                      }
                      public int Population
                      {
                          get { return population; }
                          set
                          {
                              if (value < MinPopulation)
                                  throw new ArgumentOutOfRangeException(
                                      "Population",
                                      string.Format("Population cannot be less than {0}", MinPopulation));
                              population = value;
                              OnPopulationChanged(EventArgs.Empty);
                          }
                      }
                      
                      protected virtual void OnPopulationChanged(EventArgs e)
                      {
                          EventHandler eh = PopulationChanged;
                          if (eh != null)
                              eh(this, e);
                      }
                      public static int CompareName(City first, City second)
                      {
                          if (object.ReferenceEquals(first, second)) // same reference or both null
                              return 0;
                          if (object.ReferenceEquals(first, null)) // first null?
                              return -1;
                          if (object.ReferenceEquals(second, null)) // second null?
                              return 1;
                          return first.name.CompareTo(second.name); // neither null and different reference so compare
                      }
                      public static int ComparePopulation(City first, City second)
                      {
                          if (object.ReferenceEquals(first, second)) // same reference or both null
                              return 0;
                          if (object.ReferenceEquals(first, null)) // first null?
                      
                      N 1 Reply Last reply
                      0
                      • D DaveyM69

                        There have been several things suggested but you don't seem to be understanding it, I'll try to help. You seem to be getting confused about how much data you have. You only have ONE collection of cities, you just happen to be showing the individual bits of information (name, population) on two seperate controls. The first thing to do is to get your information into one City class and provide methods for sorting based on name or population - something like:

                        public class City
                        {
                        public const int MinPopulation = 0;

                        public event EventHandler PopulationChanged;
                        
                        private string name;
                        private int population;
                        
                        public City(string name, int population)
                        {
                            if (string.IsNullOrEmpty(name))
                                throw new ArgumentNullException("name", "Name cannot be null or empty");
                            // Do more validation here for only whitespace etc
                        
                            if (population < MinPopulation)
                                throw new ArgumentOutOfRangeException(
                                    "population",
                                    string.Format("Population cannot be less than {0}", MinPopulation));
                            this.name = name;
                            this.population = population;
                        }
                        
                        public string Name
                        {
                            get { return name; }
                        }
                        public int Population
                        {
                            get { return population; }
                            set
                            {
                                if (value < MinPopulation)
                                    throw new ArgumentOutOfRangeException(
                                        "Population",
                                        string.Format("Population cannot be less than {0}", MinPopulation));
                                population = value;
                                OnPopulationChanged(EventArgs.Empty);
                            }
                        }
                        
                        protected virtual void OnPopulationChanged(EventArgs e)
                        {
                            EventHandler eh = PopulationChanged;
                            if (eh != null)
                                eh(this, e);
                        }
                        public static int CompareName(City first, City second)
                        {
                            if (object.ReferenceEquals(first, second)) // same reference or both null
                                return 0;
                            if (object.ReferenceEquals(first, null)) // first null?
                                return -1;
                            if (object.ReferenceEquals(second, null)) // second null?
                                return 1;
                            return first.name.CompareTo(second.name); // neither null and different reference so compare
                        }
                        public static int ComparePopulation(City first, City second)
                        {
                            if (object.ReferenceEquals(first, second)) // same reference or both null
                                return 0;
                            if (object.ReferenceEquals(first, null)) // first null?
                        
                        N Offline
                        N Offline
                        nassimnastaran
                        wrote on last edited by
                        #11

                        Okey , Thanks , My Means is the same that u wrote , Thanks!

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups