如何在ListBox中查找项目?

时间:2016-01-11 23:56:04

标签: c# visual-studio-2012 listbox

我正在创建一个应用程序,其中我有一个ListBox,其中包含使用StreamReader从文本文件中读取的项目。我创建了一个搜索表单,但我不确定下一步该怎么做。请问有人能给我一些建议吗?这是我的代码:

ListBox的代码(对不起,这么久)

public partial class frmSwitches : Form
{
    public static ArrayList switches = new ArrayList();
    public static frmSwitches frmkeepSwitches = null;
    public static string inputDataFile = "LeckySafe.txt";
    const int numSwitchItems = 6;
    public frmSwitches()
    {
        InitializeComponent();
        frmkeepSwitches = this;
    }

    private void btnDevices_Click(object sender, EventArgs e)
    {
        frmDevices tempDevices = new frmDevices();
        tempDevices.Show();
        frmkeepSwitches.Hide();
    }

    private bool fileOpenForReadOK(string readFile, ref StreamReader dataIn)
    {
        try
        {
            dataIn = new StreamReader(readFile);
            return true;
        }
        catch (FileNotFoundException notFound)
        {
            MessageBox.Show("ERROR Opening file (when reading data in) - File could not be found.\n"
                + notFound.Message);
            return false;
        }
        catch (Exception e)
        {
            MessageBox.Show("ERROR Opening File (when reading data in) - Operation failed.\n"
                + e.Message);
            return false;
        }

    }

    private bool getNextSwitch(StreamReader inNext, string[] nextSwitchData)
    {
        string nextLine;
        int numDataItems = nextSwitchData.Count();

        for (int i = 0; i < numDataItems; i++)
        {
            try
            {
                nextLine = inNext.ReadLine();
                if (nextLine != null)
                    nextSwitchData[i] = nextLine;
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("ERROR Reading from file.\n" + e.Message);
                return false;
            }
        }
        return true;
    }

    private void readSwitches()
    {
        StreamReader inSwitches = null;
        Switch tempSwitch;
        bool anyMoreSwitches = false;
        string[] switchData = new string[numSwitchItems];

        if (fileOpenForReadOK(inputDataFile, ref inSwitches))
        {
            anyMoreSwitches = getNextSwitch(inSwitches, switchData);

            while (anyMoreSwitches == true)
            {
                tempSwitch = new Switch(switchData[0], switchData[1], switchData[2], switchData[3], switchData[4], switchData[5]);

                switches.Add(tempSwitch);

                anyMoreSwitches = getNextSwitch(inSwitches, switchData);
            }
        }

        if (inSwitches != null) inSwitches.Close();
    }

    public static bool fileOpenForWriteOK(string writeFile, ref StreamWriter dataOut)
    {
        try
        {
            dataOut = new StreamWriter(writeFile);
            return true;
        }
        catch (FileNotFoundException notFound)
        {
            MessageBox.Show("ERROR Opening file (when writing data out)" +
                "- File could not be found.\n" + notFound.Message);
            return false;
        }
        catch (Exception e)
        {
            MessageBox.Show("ERROR Opening File (when writing data out)" +
                "- Operation failed.\n" + e.Message);
            return false;
        }

    }

    public static void writeSwitches()
    {
        StreamWriter outputSwitches = null;

        if (fileOpenForWriteOK(inputDataFile, ref outputSwitches))
        {
            foreach (Switch currSwitch in switches)
            {
                outputSwitches.WriteLine(currSwitch.getSerialNo());
                outputSwitches.WriteLine(currSwitch.getType());
                outputSwitches.WriteLine(currSwitch.getInsDate());
                outputSwitches.WriteLine(currSwitch.getElecTest());
                outputSwitches.WriteLine(currSwitch.getPatId());
                outputSwitches.WriteLine(currSwitch.getNumDevice());

            }
            outputSwitches.Close();
        }

        if (outputSwitches != null) outputSwitches.Close();
    }

    private void showListOfSwitches()
    {
        lstSwitch.Items.Clear();

        foreach (Switch b in switches)
            lstSwitch.Items.Add(b.getSerialNo()
                + b.getType() + b.getInsDate()
                + b.getElecTest() + b.getPatId() + b.getNumDevice());
    }

我的搜索表单代码:

private void btnSearch_Click(object sender, EventArgs e)
    {
        frmSearchSwitch tempSearchSwitch = new frmSearchSwitch();
        tempSearchSwitch.Show();
        frmkeepSwitches.Hide();
    } 

1 个答案:

答案 0 :(得分:0)

如果你不能使用List<T>和lambda,那么就不要再进一步了。

这里我使用List<T>作为ListBox的数据源,并将数据模拟为数据的来源并不重要但在这里我专注于搜索使用select的类中的属性为特定项目索引项目,然后在这种情况下搜索的位置),如果发现索引用于移动到项目。没有代码,如果没有找到,因为如果这里的代码对你来说是很容易的话,这很容易做到。

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

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

        private void Button1_Click(object sender, EventArgs e)
        {
            var results =
                ((List<Item>)ListBox1.DataSource)
                    .Select((data, index) => new 
                    { Text = data.SerialNumber, Index = index })
                    .Where((data) => data.Text == "BB1").FirstOrDefault();
            if (results != null)
            {
                ListBox1.SelectedIndex = results.Index;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var items = new List<Item>() {
            new Item {Identifier = 1, SerialNumber = "AA1", Type = "A1"},
            new Item {Identifier = 2, SerialNumber = "BB1", Type = "A1"},
            new Item {Identifier = 3, SerialNumber = "CD12", Type = "XD1"}
        };
            ListBox1.DisplayMember = "DisplayText";
            ListBox1.DataSource = items;
        }
    }
    /// <summary>
    /// Should be in it's own class file
    /// but done here to keep code together
    /// </summary>
    public class Item
    {
        public string SerialNumber { get; set; }

        public string Type { get; set; }

        public int Identifier { get; set; }

        public string DisplayText
        {
            get
            {
                return SerialNumber + " " + this.Type;
            }
        }
    }
}