使用列表框,如何找到确切的对象?

时间:2017-03-03 14:37:20

标签: c# listbox

我认为这是一个有点简单的答案,但我无法理解如何做到这一点。

我有一个对象(让我们称之为A)与其他对象的列表(例如地方) 所以我创建了一个Web应用程序,在那个页面中我有一个地方列表框(我使用地方名称(字符串)作为唯一ID)。问题是当我从该列表中选择一个项目时,如何在地点列表中找到该项目?

例如:

page.aspx:

 <p style="margin-left: 40px">
    Select place:</p>
<p style="margin-left: 40px">
    <asp:ListBox ID="listplace" runat="server"></asp:ListBox>
</p>

page.aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
     {
       if (!IsPostBack)
        {
            listplace.DataSource = A.listOfPlaces;
            listplace.DataBind();
        }
     }

2 个答案:

答案 0 :(得分:0)

您可以尝试:

string currPlace = listplace.SelectedItem.ToString();
string place = A.listOfPlaces.Where
    (x => x.Contains(currPlace)).FirstOrDefault();

答案 1 :(得分:0)

希望这可以帮到你:

using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace ListBox_42581647
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Doit();
        }

        private void Doit()
        {
            ListBox lb = new ListBox();//create a listbox
            lb.Items.Add(new aPlace { placename = "TheBar", placeCoolFactor = "booze" });//add something to the listbox
            lb.Items.Add(new aPlace { placename = "TheHouse", placeCoolFactor = "bowl"});//add something to the listbox
            lb.Items.Add(new aPlace { placename = "ThePark", placeCoolFactor = "dogs" });//add something to the listbox

            lb.SelectedItem = lb.Items[1];//lets fake a selection

            var theSelectedPlace = lb.SelectedItem;//the actual item selected
            var theSelectedPlaceName = ((aPlace)lb.SelectedItem).placename;//the selected item place name
            var theSelectedPlaceCoolFactor = ((aPlace)lb.SelectedItem).placeCoolFactor;//the selected item place cool factor


            //now I'll create your (lets call it A)
            List<aPlace> parallelList = new List<aPlace>();//lets call it A
            parallelList.Add((aPlace)lb.Items[0]);//This list contains the same items your ListBox contains
            parallelList.Add((aPlace)lb.Items[1]);//This list contains the same items your ListBox contains
            parallelList.Add((aPlace)lb.Items[2]);//This list contains the same items your ListBox contains

            //find the selected by matching the selected Placename
            aPlace theChosenPlace = parallelList.Where(p => p.placename == theSelectedPlaceName).FirstOrDefault();
            //find the selected by matching the actual item
            aPlace theChosenPlace2 = parallelList.Where(p => p == theSelectedPlace).FirstOrDefault();
        }

    }

    public class aPlace
    {
        public string placename { get; set; }
        public string placeCoolFactor { get; set; }
    }


}