![](/img/trans.png)
[英]How to move multiple selected item from one listbox to another listbox?
[英]How do I populate a listbox based on a selected item from another listbox?
当我的表单加载时,我有两个列表框(Regions和Divisions),“区域”列表框填充了4个区域(中西部,东北,南,西)。 当我单击这些区域之一时,我希望“分区”列表框填充与所单击区域相关的分区。 我正在通过与SQL db通信的数据存储库进行工作。 表格加载时的初始填充
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();
}
}
从数据库获取区域划分的方法:
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();
}
}
在“ Regions
列表框的SelectedIndexChanged
事件中,获取所选区域,然后在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>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.