[英]How do I get the selected values in a listbox?
我有一個Winforms應用程序,它有一個可以選擇的值列表框。 我希望選定的值在編輯表單上顯示為選中狀態。 這是加載代碼:
private void LoadListBox()
{
DataTable dt = new DataTable();
string[] names = new string[] { "UID1", "UID2", "UID3","UID4" };
dt.Columns.Add("Units", typeof(string));
dt.Columns.Add("Value", typeof(int));
int count = 1;
foreach (string value in names)
{
DataRow drRow = dt.NewRow();
drRow["Units"] = value;
drRow["Value"] = count;
count++;
dt.Rows.Add(drRow);
}
listBox1.DisplayMember = "Units";
listBox1.ValueMember = "Value";
listBox1.DataSource = dt;
}
如果他們選擇UID1
和UID2
它被存儲為1
, 2
在數據庫中。
如果用戶單擊編輯按鈕,則UID1
, UID2
應為選定值,但應加載所有值。
當單擊edit
按鈕時,如何確保所選內容顯示為已選擇?
枚舉每個列表框項並根據您的規則將其設置為選中或不選:
for (int index = 0; index < listBox1.Items.Count; index++ )
{
Object o = (int)listBox1.Items[index];
if ( /* criteria you want here */ )
{
listBox1.SetSelected(index, true);
}
}
除非您在回發事件中設置數據源,否則在回發期間將保留所選值,從而“覆蓋”它。
所以在你的代碼中只有這樣的
if
語句:
if (!Page.IsPostBack) LoadListBox();
對不起,以為是ASP.NET - 與WinForms環境無關。 其他答案已經滿足您的需求。 :)
嘗試SelectedItems.Add函數。 您可以將所需的每個項目添加到當前選擇中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.