Search code examples
c#xmltextboxpopulate

C# : Populating form fields based on user selection using an XML file


On my form, I have 2 fields set up. Location of item, and sub-area. I am trying to populate the sub-area field based on what location the user chooses. For instance, they choose "Location 4". The only 3 sub-areas for that location are, lets say, A, B, and C. Upon selection in the location box, the sub-area box will only display A, B, and C. I have all the locations and allowed sub areas in an xml file called appsettings.xml. How do I get the program to read in the xml file and allow the sub area field to only be populated with valid data? Below is an example of how I have my xml file set up.

<?xml version="1.0" encoding="utf-8" ?> 
 <MerchandiseTrack>

   <Merchandise_Zones Application_Data="Test-Run">

      <KeyBoard_App>
        <AppString>c windows osk.exe</AppString> 
      </KeyBoard_App>

 <Storage_Location>

     <head id="Location">                // Name of box on app
       <body id="04">                    // Name of Location within the box
         <Sub-Area>A, B, C,</Sub-Area>   // Allowed sub-areas
       </body>
     </head>

     <head id="Location">                // Name of box on app  
      <body id="05">                     //Name of Location within the box
         <Sub-Area>P, L, R, B</Sub-Area> // Allowed sub-areas 
      </body>
     </head>

     <head id="Location">                // Name of box on app
      <body id="14">                     //Name of Location within the box
       <Sub-Area>A, X, C </Sub-Area>     //Name of Location within the box
      </body>
    </head>

  </Storage_Location>
 </Merchandise_Zones>
</MerchandiseTrack>

Solution

  • You set a event on SelectedIndexChanged. Then you read the locationID and select the node from your file:

            XmlDocument doc = new XmlDocument();
            doc.Load(@"path/to/file.xml");
            XmlNode subarea = doc.SelectSingleNode("/MerchandiseTrack/Merchandise_Zones/Storage_Location/head/body[@id=" + locationComboBox.SelectedItem.ToString()+ "]/Sub-Area");
            string[] areas = subarea.InnerText.Split(',');
            foreach (string area in areas)
            {
               subAreaComboBox.Items.Add(area);
            }
    

    That includes that you do not (!) have a trailing comma on your list (as you have with your first location at the moment. If so, you have to extend the code to remove it.