本文介绍了从集合中获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Documents
的类我有一个名为class StoreObjects:List< Documents>
的集合
我正在从Form1中向集合中输入数据

这是Form1中代码的一部分"

StoreObjects so = new StoreObjects();

d =新文档(txtName.Text,txtSurname.Text,txtTitle.Text);
so.Add(d);

到目前为止,我设法输入甚至显示了数据.

我现在想要的是来自Form2的文件,我希望能够按标题进行搜索,如果我从Form1进行搜索,这是可行的,但是Form2却不起作用

I have a class named Documents
I have a collection named class StoreObjects:List<Documents>

I am entering data into the collection from a Form1

"this is part of the code in Form1"

StoreObjects so = new StoreObjects();

d = new Documents(txtName.Text, txtSurname.Text, txtTitle.Text);
so.Add(d);

so far I managed to enter data and even display it.

What I want now is from Form2, I want to be able to search by title, if I do it from Form1 this works but from Form2 does not work

so.SearchByTitle(txtTitle.Text);
            Console.WriteLine(so.foundTitle);
            if (so.foundTitle == false)
            {
                Console.WriteLine("Not Found");
            }




这就是我在StoredObject中拥有的




this is what i have in StoredObject

public bool SearchByTitle(string aTitle)
        {
            foreach (Documents d in this)
            {
                if ((d != null) && (d.Title == aTitle))
                {
                    foundTitle = true;
                    Console.WriteLine(d.GetData());
                }
            }
            return foundTitle;
        }




我认为这是因为表格2中的声明
StoreObjects so = new StoreObjects();

我该如何设法获得想要的结果?




I think that it is because of this declaration in Form 2
StoreObjects so = new StoreObjects();

how can I manage to get the results I want

推荐答案


pubic static class Globals
{
    public static StoredObjects StoredObjects { get; set; }

    private Globals()
    {
        StoredObjects = new StoredObjects();
    }
}



您可以这样称呼:



You call it like so:

if (Globals.StoredObjects != null)
{
   ...
}






{
   Form2 form2 = new Form2(lvTest1, cmbTest2);
   form2.ShowDialog(this);
}

在form2.cs下

under the form2.cs

public partial class Form2 : Form
    {
        ListView lv = new ListView();
        ComboBox cb = new ComboBox();
        public Form2(ListView lvParents, ComboBox cbParent)
        {
            InitializeComponent();
            lv = lvParents;
            cb = cbParent;
        }
     }



因此您可以根据给定的示例修改代码.



so you can modify your code, based on given example.


这篇关于从集合中获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 02:14