简体   繁体   中英

How do I populate a listbox based on a selected item from another listbox?

I have two listboxes(Regions and Divisions) when my form loads the Regions listbox is populated with 4 regions(Midwest, NorthEast, South, West). When I click on one of those regions I want the Divisions listbox to populate with the divisions that relate to the region that was clicked. I am working through a data repository that communicates with my SQL db. Initial population upon form load

StateRepository sr = new StateRepository();
foreach (string s in sr.GetRegions())
{
    lstRegions.Items.Add(s);
}

Code behind the GetRegions method:

public IEnumerable<string> GetRegions()
{
    try
    {
        List<string> results = new List<string>();
        using (var conn = new SqlConnection(Settings.Default.StateAnalysisConnection))
        {
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = "Select * From Regions ";
                conn.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        results.Add((string)reader["Region"]);
                    }
                }
            }
         }

         return results;
    }
    catch (Exception ex)
    {
        throw new Exception("Database error in StateRepository", ex);
    }
    finally
    {
        if (connection.State == ConnectionState.Open)
            connection.Close();
    }
}

The method that gets the divisions in region from the db:

public IEnumerable<string> GetDivisionsInRegion(string region)
{
    try
    {
        List<string> results = new List<string>();
        var divisions = new List<string>();
        using (var conn = new SqlConnection(Settings.Default.StateAnalysisConnection))
        {
            using (var cmd = conn.CreateCommand())
            {
                 cmd.CommandText = "Select Division From Divisions "
                    + "Where Region = '" + region + "'";
                 conn.Open();
                 using (var reader = cmd.ExecuteReader())
                 {
                     while (reader.Read())
                     {
                         results.Add((string)reader["Division"]);
                     }
                 }
             }
         }

         return results;
     }
     catch (Exception ex)
     {
         throw new Exception("Database error in StateRepository", ex);
     }
     finally
     {
         if (connection.State == ConnectionState.Open)
             connection.Close();
     }
}

In the SelectedIndexChanged event of your Regions listbox, get the selected region then use that in your GetDivisionsInRegion method and populate the Divisions listbox with the result.

private void Regions_SelectedIndexChanged(object sender, System.EventArgs e)
{
   // Get the currently selected item in the ListBox. 
   string region = Regions.SelectedItem.ToString();

   // Find the divisions in the region
   IEnumerable<string> divisions = GetDivisionsInRegion(region);

   //set as this as the new data source for your Divisions listbox
   Divisions.DataSource = divisions;
}

Although I think you may have to either cast the divisions to List<string> or get your GetDivisionsInRegion to return a List<string> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM