簡體   English   中英

使用List從listBox獲取值

[英]Get value from listBox using List

我正在使用ListBox ,數據是一個類:

private class Duration
{
    public int Value { get; set; }
    public string Label { get; set; }
}

我以這種方式綁定類:

var durations = new List<Duration>() 
  {
    new Duration() { Value = 5, Label = "5 minutes" }, 
    new Duration() { Value = 10, Label = "10 minutes" }, 
    new Duration() { Value = 15, Label = "15 minutes" }, 
    new Duration() { Value = 30, Label = "30 minutes" }, 
    new Duration() { Value = 45, Label = "45 minutes" }, 
    new Duration() { Value = 60, Label = "1 hour" }, 
    new Duration() { Value = 90, Label = "1 hour and half" } 
  };
this.listTime.DataSource = durations;
this.listTime.DisplayMember = "Label";
this.listTime.ValueMember = "Value";

一切正常,並顯示標簽。 當我去讀取所選的值時,我無法恢復所選項目的值。

我期望能夠做到這一點:

int value = listTime.SelectedItems[0].Value;

或至少這樣:

Duration value = listTime.SelectedItems[0];

但這給了我錯誤,我做錯了什么? 如何在ListBox上獲取所選項目的值的正確方法?

if (listTime.SelectedIndex != -1)
{
    var item = listTime.SelectedItem as Duration;
    //or as suggested by 'Stu'
    var item = (Duration)listTime.SelectedItem;
    MessageBox.Show(item.Value.ToString());
}

如果使用列表框,則此代碼可以:

listTime.Items[0].Value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM