![](/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.