[英]Highlight Combobox when SelectedValue is not in ItemsSource
[英]Problem with SelectedValue when Sorted is true (ComboBox)
將ComboBox.Sorted
設置為true
, ComboBox.SelectedValue
返回的值與可見選擇的值不同。
加載項目並顯示:
using (ModelContext model = new ModelContext())
{
cbWorker.ValueMember = "IdWorker";
cbWorker.DisplayMember = "FullName";
bindingWorker.DataSource = model.Workers.Select(x => new ItemWorker{
IdWorker = x.Id,
FullName = x.FullName
})
.ToList();
cbWorker.DataSource = bindingWorker;
}
private void CbWorker_SelectedValueChanged(object sender, EventArgs e)
{
object x = cbWorker.SelectedValue;
if (x!= null) label.Text = x.ToString();
}
如果ComboBox.Sorted = false
,則SelectedValue
為OK:
但是如果ComboBox.Sorted = true
,則SelectedValue
不正常:
有可能解決它嗎? 與CheckedListBox
類似的問題。
設置ComboBox.Sorted
以false
和排序bindingWorker.DataSource
由IdWorker
屬性:
cbWorker.Sorted = false;
...
bindingWorker.DataSource = model.Workers.Select(x => new ItemWorker{
IdWorker = x.Id,
FullName = x.FullName
})
.OrderBy(x => x.IdWorker)
.ToList();
cbWorker.DataSource = bindingWorker;
cbWorker.ValueMember = "IdWorker";
cbWorker.DisplayMember = "FullName";
您的示例中有兩個問題:
嘗試在數據綁定控件上設置Sorted屬性會引發ArgumentException。 您必須使用基礎數據模型對數據進行排序。
在數據綁定的ComboBox
上將ComboBox.Sorted
設置為true
可能不是一個好主意。 即使它沒有拋出異常,也可能導致意外行為。
一個簡單的測試可以顯示如果ComboBox.Sorted = true
:
ComboBox.DisplayMember
排序 item.ToString()
) 這意味着即使ComboBox.DisplayMember
是一個數字類型,它也會在每個數字上調用ToString()
之后進行排序,因此這些項目將按字母順序排序 ,而不是數字。
例如,如果數字10, 1, 3
將直接排序為數值,它們將被排序為1, 3, 10
,但如果數字將首先轉換為字符串( "10", "1", "3"
)並且除了排序之外,它們將按字母順序排序為"1", "10", "3"
如果你想:
ComboBox
排序 ComboBox
項目 DisplayMember
以外的成員排序 你必須設定的項目,如前對項目進行排序ComboBox.DataSource
並設置ComboBox.Sorted
到false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.