2011-06-28 76 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);