使用ListBox,如何找到该确切的对象



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

我有一个对象(我们称其为a),带有其他对象列表(例如,位置)因此,IM创建一个WebApp,在该页面中,我有一个listbox的位置框(IM使用loce(String)作为唯一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();
        }
     }

希望这可以帮助您:

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; }
    }

}

您可以尝试:

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

最新更新