嘿。我有以下代碼填充我的列表框中列表框和數據源 - 防止選擇第一項
UsersListBox.DataSource = GrpList;
然而,填充盒後,在列表中的第一項被默認選中與「選擇指數改變」事件觸發。如何防止在列表框填充後立即選擇項目,或者如何防止事件發生?
感謝
嘿。我有以下代碼填充我的列表框中列表框和數據源 - 防止選擇第一項
UsersListBox.DataSource = GrpList;
然而,填充盒後,在列表中的第一項被默認選中與「選擇指數改變」事件觸發。如何防止在列表框填充後立即選擇項目,或者如何防止事件發生?
感謝
從點火保留的情況下,這裏是我在過去使用的兩個選項:
註銷事件處理程序在設置數據源。
UsersListBox.SelectedIndexChanged -= UsersListBox_SelectedIndexChanged;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
UsersListBox.SelectedIndexChanged += UsersListBox_SelectedIndexChanged;
創建一個布爾型標誌來忽略該事件。
private bool ignoreSelectedIndexChanged;
private void UsersListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (ignoreSelectedIndexChanged) return;
...
}
...
ignoreSelectedIndexChanged = true;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
ignoreSelectedIndexChanged = false;
也許DataSourceChanged你可以檢查的SelectedIndex的狀態,如果你的幸運,你可以再正義的力量的SelectedIndex = -1。
如果你只是想清除選定的值,你可以用你ClearSelected設置DataSource後。但是如果你不想讓事件發生,那麼你將不得不使用約瑟夫的方法之一。
這不是一個相關的答案。 – 2013-06-14 05:53:51
好吧,它看起來像ListBox.DataSource設置後自動選擇第一個元素。其他解決方案很好,但它們不能解決問題。這是我怎麼解決這個問題:
// Get the current selection mode
SelectionMode selectionMode = yourListBox.SelectionMode;
// Set the selection mode to none
yourListBox.SelectionMode = SelectionMode.None;
// Set a new DataSource
yourListBox.DataSource = yourList;
// Set back the original selection mode
yourListBox.SelectionMode = selectionMode;
該解決方案工作正常,比其他解決方案更簡單 – 2016-10-25 10:10:16
我使用下面,似乎爲我工作:
List<myClass> selectedItemsList = dataFromSomewhere
//Check if the selectedItemsList and listBox both contain items
if ((selectedItemsList.Count > 0) && (listBox.Items.Count > 0))
{
//If selectedItemsList does not contain the selected item at
//index 0 of the listBox then deselect it
if (!selectedItemsList.Contains(listBox.Items[0] as myClass))
{
//Detach the event so it is not called again when changing the selection
//otherwise you will get a Stack Overflow Exception
listBox.SelectedIndexChanged -= listBox_SelectedIndexChanged;
listBox.SetSelected(0, false);
listBox.SelectedIndexChanged += listBox_SelectedIndexChanged;
}
}
設置IsSynchronizedWithCurrentItem="False"
,也SelectedIndex=-1
和每一件事應該爲你
說工作什麼?如果你幸運?而我甚至不明白你的答案實際上在說什麼。 – 2013-06-14 05:55:20