如何根据另一个列表框中的选定项目填充列表框?

时间:2014-11-25 02:44:27

标签: c# winforms listbox

我的表单加载时,我有两个列表框(区域和分区)区域列表框中填充了4个区域(中西部,东北,南,西)。当我点击其中一个区域时,我希望Divisions列表框填充与所单击区域相关的分区。我正在处理与我的SQL数据库通信的数据存储库。 表格载荷时的初始人口

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

GetRegions方法背后的代码:

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();
    }
}

从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();
     }
}

1 个答案:

答案 0 :(得分:1)

SelectedIndexChanged列表框的Regions事件中,获取所选区域,然后在GetDivisionsInRegion方法中使用该区域,并使用结果填充Divisions列表框。

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;
}

虽然我认为您可能需要将分部转换为List<string>或让GetDivisionsInRegion返回List<string>