Search code examples
c#xmlcomboboxxmlreader

Populate combobox from XML in XmlReader in C#


I have to read XML and populate combobox in C#. Here is what I tried:

private class Item 
{
  public string Name;
  public int Id

  public Item(string name, int id) 
  {
      Name = name; 
      Id = id;
  }
}   

And here is my XmlReader code:

if (reader.IsStartElement())
{
    //return only when you have START tag
    switch (reader.Name.ToString())
    {
        case "Ad_Ref":
            Console.WriteLine("Name of the Element is : " + reader.ReadString());
            break;

        case "Ad_Id":
            Console.WriteLine("Your Id is : " + reader.ReadString());
            break;
    }
}

How I can do like this comboBox1.Items.Add(new Item("Student 1", 1));

My XML has only two tags, One is Ad_Id and other is Ad_Ref.

UPDATED: Here is XML Sample

<Listings>
 <Listing>
  <Ad_Id>1</Ad_Id>
 <Ad_Ref>admin</Ad_Ref>
  </Listing>
 </Listings>

Solution

  • If you are opting for XmlReader you could do something like that:

    XmlReader.ReadToFollowing is used to read the sibling element node.

    var lstItems = new List<Item>();
    using(XmlReader reader = XmlReader.Create("test.xml"))
    {
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
    
                if (reader.Name == "Ad_Id")
                {
                    reader.Read();
                    string sAd_ID = reader.Value;
                    string sAd_Ref = string.Empty;
    
                    if (reader.ReadToFollowing("Ad_Ref"))
                    {
                         reader.Read();
                         sAd_Ref = reader.Value;
                    }
    
                     if(!string.IsNullOrEmpty(sAd_ID) && sAd_Ref != string.Empty)                        
                         lstItems.Add(new Item(sAd_Ref, Convert.ToInt32(sAd_ID)));
                }
         }
     }
    

    You could populate List<Item> as lstItems above and bind it with ComboBox.

    comboBox1.DataSource = lstItems;
    comboBox1.DisplayMember="Name";
    comboBox1.ValueMember="Id";    
    

    UPDATE:

    Change access modifier of class to public and add property getter and setter.

    public class Item
    {
        public string Name { get; set; }
        public int Id { get; set; }
    
        public Item(string name, int id)
        {
            Name = name;
            Id = id;
        }
    }