我的表单加载时,我有两个列表框(区域和分区)区域列表框中填充了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();
}
}
答案 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>
。