WinForm ListBox 詳解與案例
一、核心概念
?ListBox? 是 Windows 窗體中用于展示可滾動列表項的控件,支持單選或多選操作,適用于需要用戶從固定數據集中選擇一項或多項的場景?。
二、核心屬性
屬性 | 說明 |
---|---|
?Items? | 管理列表項的集合,支持動態增刪(如 Add()、Remove())?。 |
?SelectedIndex? | 獲取或設置選中項的索引(未選中時為 -1)?。 |
?SelectedItem? | 獲取當前選中的項對象?。 |
?SelectionMode? | 設置選擇模式:Single(默認)、MultiSimple 或 MultiExtended?。 |
?Sorted? | 是否按字母順序自動排序項?。 |
?ScrollAlwaysVisible? | 始終顯示滾動條(即使內容未超出可視區域)?。 |
三、核心方法與事件
1?、常用方法?
- Items.Add()?:添加新項?。
listBox1.Items.Add("新項");
。?Items.RemoveAt()?:根據索引刪除項?
listBox1.Items.RemoveAt(0); // 刪除第一項
- ClearSelected()?:取消所有選中項?。
2?、重要事件?
?SelectedIndexChanged?:選中項變化時觸發?。
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {if (listBox1.SelectedItem != null) {MessageBox.Show($"選中項:{listBox1.SelectedItem}");}
}
四、完整案例
案例1:動態增刪項
?需求?:通過按鈕動態添加和刪除列表項。
?實現代碼?:
// 添加項
private void btnAdd_Click(object sender, EventArgs e) {listBox1.Items.Add(txtInput.Text);txtInput.Clear();
}// 刪除選中項
private void btnDelete_Click(object sender, EventArgs e) {if (listBox1.SelectedIndex != -1) {listBox1.Items.RemoveAt(listBox1.SelectedIndex);}
}
?說明?:輸入框 txtInput 用于接收用戶輸入,刪除時需檢查是否有選中項?。
案例2:多選操作與數據綁定
?需求?:從數據庫加載數據并支持多選。
?實現代碼?:
// 綁定數據源(示例使用List模擬數據庫數據)
private void Form1_Load(object sender, EventArgs e) {List<string> data = new List<string> { "北京", "上海", "廣州", "深圳" };listBox1.DataSource = data;listBox1.SelectionMode = SelectionMode.MultiExtended; // 啟用擴展多選
}// 獲取所有選中項
private void btnShowSelected_Click(object sender, EventArgs e) {var selectedItems = listBox1.SelectedItems.Cast<string>().ToList();MessageBox.Show($"選中城市:{string.Join(", ", selectedItems)}");
}
?說明?:DataSource 屬性支持綁定集合數據,SelectionMode 控制多選模式?。
案例3:排序與批量刪除
?需求?:自動排序列表項,并批量刪除符合條件的項。
?實現代碼?:
// 啟用排序
listBox1.Sorted = true;// 批量刪除包含“測試”的項
private void btnBatchDelete_Click(object sender, EventArgs e) {for (int i = listBox1.Items.Count - 1; i >= 0; i--) {if (listBox1.Items[i].ToString().Contains("測試")) {listBox1.Items.RemoveAt(i); // 倒序刪除避免索引錯位}}
}
?說明?:倒序遍歷避免因刪除導致索引變化?。
五、注意事項
?性能優化?:批量操作時使用 BeginUpdate() 和 EndUpdate() 減少界面刷新次數?。
listBox1.BeginUpdate();
for (int i = 0; i < 1000; i++) {listBox1.Items.Add($"Item {i}");
}
listBox1.EndUpdate();
?索引管理?:刪除多項時需倒序操作,避免索引越界?。
總結
ListBox 是 WinForm 中靈活且功能豐富的列表控件,通過合理使用 Items 集合、SelectionMode 及事件機制,可實現動態數據管理、多選交互等復雜場景。開發時需注意性能優化和索引邏輯,避免常見錯誤?