DropDownList的项目找到部分值 [英] dropdownlist items find by partial value

查看:135
本文介绍了DropDownList的项目找到部分值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要找到一个项目(并选择它),使用的值在DropDownList中,我们简单地做

To find an item (and select it) in a dropdownlist using a value we simply do

dropdownlist1.Items.FindByValue("myValue").Selected = true;



如何才能找到使用部分值的项目?说我有3个元素,它们的值分别为myvalue的一,myvalue的二,三myvalue的。我想要做这样的事情。

How can I find an item using partial value? Say I have 3 elements and they have values "myValue one", "myvalue two", "myValue three" respectively. I want to do something like

dropdownlist1.Items.FindByValue("three").Selected = true;

和有它选择的最后一个项目。

and have it select the last item.

推荐答案

您可以从lsit的结束迭代,并检查是否值中包含的项目(这将选择包含值的最后一个项目myvalue的)。

You can iterate from the end of the lsit and check if value contains the item (this will select the last item which contains value "myValue").

 for (int i = DropDownList1.Items.Count-1; i >0 ; i--)
        {
            if (DropDownList1.Items[i].Value.Contains("myValue"))
            {
                DropDownList1.Items[i].Selected = true;
                break;
            }
        }



或者你可以LINQ一如既往的使用:

Or you can use linq as always:

DropDownList1.Items.Cast<ListItem>()
                   .Where(x => x.Value.Contains("three"))
                   .LastOrDefault().Selected = true;

这篇关于DropDownList的项目找到部分值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆