[英]how to get DisplayMemeber value from listbox by valuemember c#?
I have a listBox, something like this: 我有一个listBox,像这样:
ID ClientName ID ClientName
Now, I know the ID of the client , how do i get the DisplayMember of it ? 现在,我知道了客户端的ID,我如何获取它的DisplayMember?
转换为DataRowView
并转换为按索引选择客户端名称列,即1。
String ClientName = (((DataRowView) listBox1.SelectedItem).Row[1]).ToString();
You could try this code. 您可以尝试此代码。 the example is written if the
DataSource
of the Listbox
is DataTable
, but if it is something else, try to see of what type is the object
in Items property of the ListBox
. 如果
Listbox
的DataSource
是DataTable
,则编写该示例,但如果还有其他内容,请尝试查看ListBox
Items属性中的object
是什么类型。
(Note that I don't like using break
statement but this was the quickest way) (请注意,我不喜欢使用
break
语句,但这是最快的方法)
string str = string.Empty;
foreach (DataRowView drv in listBox1.Items)
{
int lvID = int.Parse(drv.Row[listBox1.ValueMember].ToString());
if (lvID == 5)
{
str = drv.Row[listBox1.DisplayMember].ToString();
break;
}
}
var t = from list in USStates where te.ShortName == textBox1.Text select te.LongName.ToString();
foreach(String st in t)
{
MessageBox.Show(st);
}
where USStates is Generic List and TextBox1.text contains the value of the id.Considering your listbox uses Generic list as DataSource. 其中USStates是通用列表,而TextBox1.text包含id的值。考虑到列表框,将通用列表用作数据源。
There is a much easier solution. 有一个更简单的解决方案。 Especially if you are building the DataSource, populating it, then releasing the source.
特别是如果您要构建数据源,然后填充它,然后释放源。 Use the Items list to create a DataRowView of the item currently selected.
使用“项目”列表创建当前所选项目的DataRowView。 Then just pull the right index.
然后只需拉正确的索引。 0 will give you the "value member" and 1 will give you the "display member".
0将给您“值成员”,而1将给您“显示成员”。
DataRowView thisLine = cbTrackerFormList.Items[cbTrackerFormList.SelectedIndex] as DataRowView;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.