Hello!
There are two listboxes in the first one I have differend kind of animal
category such as Bird,Mammal,Reptile and the second one should show all
those animal type that correspond to the animal category.
An example if I choose Mammal in the category listBox then in the animal
type listbox should display Bear,Cat,Deer,Lion,Dog,Horse,Panda and Wolf.
So when I choose a category only the animal that belong to the selected
animal category should be displayed in the animal type listBox.
What is the best kind of solution and what class is most suitable here ?
//Tony
This kind of problem can easily be solved with data binding. If you hate
to hard-code your data, you can load it from xml file. Example below (I
assume you already put two listboxes, named listBox1 & listBox2, on your
form)
public partial class Form1 : Form
{
private List<AnimalCategory> animals;
private readonly BindingSource animalListBinding = new BindingSource();
public Form1()
{
InitializeComponent();
ReadData();
InitListBox();
}
private void ReadData()
{
using (Stream stream = File.OpenRead("Animals.xml"))
{
var serializer = new XmlSerializer(typeof(List<AnimalCategory>));
try
{
animals = (List<AnimalCategory>)serializer.Deserialize(stream);
}
catch (InvalidOperationException)
{
MessageBox.Show(@"Unable to load data file. Application will
now exit\n");
Application.Exit();
}
}
}
private void InitListBox()
{
animalListBinding.DataSource = animals;
listBox1.DataSource = animalListBinding;
listBox1.DisplayMember = "Name";
listBox2.DataSource = animalListBinding;
listBox2.DisplayMember = "Animals.Name";
}
}
public class Animal
{
[XmlText]
public string Name { get; set; }
}
public class AnimalCategory
{
[XmlAttribute]
public string Name { get; set; }
[XmlElement("Animal")]
public List<Animal> Animals { get; set; }
}
Animals.xml
<?xml version="1.0"?>
<ArrayOfAnimalCategory
xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="
http://www.w3.org/2001/XMLSchema">
<AnimalCategory Name="Bird">
<Animal>Duck</Animal>
<Animal>Kolibri</Animal>
</AnimalCategory>
<AnimalCategory Name="Insect">
<Animal>Butterfly</Animal>
<Animal>Bee</Animal>
</AnimalCategory>
<AnimalCategory Name="Mammal">
<Animal>Cat</Animal>
<Animal>Bear</Animal>
</AnimalCategory>
<AnimalCategory Name="Marine">
<Animal>Pike</Animal>
<Animal>GoldFish</Animal>
</AnimalCategory>
<AnimalCategory Name="Reptile">
<Animal>Frog</Animal>
<Animal>Snake</Animal>
</AnimalCategory>
</ArrayOfAnimalCategory>