2011-06-28 75 views
10

這一定很容易,但我被卡住了。 我有一個X項目的列表框。每個項目都有一個文本說明(出現在列表框中)及其值(數值)。 我希望能夠使用項目的索引號獲取項目的value屬性。按索引獲取列表框項目的值

+1

WPF中,的WinForms,Silverlight的或ASP.NET? –

+0

添加一些標籤,詳細說明您正在使用的內容,如Daniel Hilgarth上面所述。 –

+0

你在使用_windows forms_應用程序嗎? –

回答

0

這個工作對我來說:

ListBox x = new ListBox(); 
x.Items.Add(new ListItem("Hello", "1")); 
x.Items.Add(new ListItem("Bye", "2")); 

Console.Write(x.Items[0].Value); 
+5

據我所知,'ListBox.Items'的類型是'System.Windows.Forms.ListBox.ObjectCollection',這意味着'ListBox.Items [index]'是一個沒有Value屬性的對象! –

+1

這是WebForms的答案,因爲他指的是「設置文本和值」,這使我可以假設WebForms,而不是WinForms。 – DaveShaw

1

假設你想的第一個項目的價值。

ListBox list = new ListBox(); 
Console.Write(list.Items[0].Value); 
3

如果您在Windows窗體的工作項目,您可以嘗試以下方法:

項目添加到ListBoxKeyValuePair對象:

listBox.Items.Add(new KeyValuePair(key, value); 

然後你就可以對它們進行檢索採用以下方式:

KeyValuePair keyValuePair = listBox.Items[index]; 
var value = keyValuePair.Value; 
+0

我試過了,但它沒有工作:( – tzam

+0

@tzam:你在使用_windows forms_應用程序嗎? –

+0

這是正確的Akram – tzam

3

我正在使用綁定帶有一個SqlDataReader的ingSource,以上都不適用於我。

質疑微軟:爲什麼這個工作:

? lst.SelectedValue 

但是,這不?

? lst.Items[80].Value 

,我覺得我必須回去到BindingSource對象,將它轉換爲System.Data.Common.DbDataRecord,然後參照其列名:

? ((System.Data.Common.DbDataRecord)_bsBlocks[80])["BlockKey"] 

現在,這只是荒謬。

+0

或者我猜我可以遍歷Items集合,選擇每個項目,然後得到SelectedValue。但是我不應該這樣做,而且它是一個kludge –

+0

在' ListBox的Items集合是類型對象,它沒有'Value'屬性,該項目可能是'DataRowView',一個複雜對象或主要類型。該值應該使用'ValueMember'屬性來計算,與'SelectedValue'工作方式相同。 –

8

這將是

String MyStr = ListBox.items[5].ToString(); 
+0

項目可能是'DataRowView'或複雜對象或其他類型。一個項目的基礎價值應該基於'ValueMember'來計算。 –

5

在這裏我無法看到即使是在這個問題的一個正確答案(中的WinForms標籤)和真奇怪,如此頻繁的問題。

ListBox控件的項目可能是DataRowView,複雜對象,匿名類型,主要類型和其他類型。一個項目的基礎價值應根據ValueMember計算。

ListBox控件有一個GetItemText它可以幫助您獲取項目文本,而不管您添加爲項目的對象的類型。它真的需要這樣的GetItemValue方法。

GetItemValue擴展方法

我們可以創建GetItemValueextension method獲得項目值,就像GetItemText

using System; 
using System.Windows.Forms; 
using System.ComponentModel; 
public static class ListControlExtensions 
{ 
    public static object GetItemValue(this ListControl list, object item) 
    { 
     if (item == null) 
      throw new ArgumentNullException("item"); 

     if (string.IsNullOrEmpty(list.ValueMember)) 
      return item; 

     var property = TypeDescriptor.GetProperties(item)[list.ValueMember]; 
     if (property == null) 
      throw new ArgumentException(
       string.Format("item doesn't contain '{0}' property or column.", 
       list.ValueMember)); 
     return property.GetValue(item); 
    } 
} 

使用上面的方法,你不必擔心ListBox並設置將返回一個項目的預期Value。它適用於List<T>Array,ArrayList,DataTable,匿名類型列表,主要類型列表以及您可以用作數據源的所有其他列表。下面是使用的例子:

//Gets underlying value at index 2 based on settings 
this.listBox1.GetItemValue(this.listBox1.Items[2]); 

因爲我們創造了GetItemValue方法擴展方法,當你想使用的方法,不要忘記包括你把類的命名空間

該方法也適用於ComboBoxCheckedListBox

0

只是試試這個 列表框是你的清單,玉是至極的指數值爲0的veriable將被分配

string yu = listBox1.Items[0].ToString(); 
MessageBox.Show(yu);