How to transfer objects between windows in C #

I got a ListView in windows form. When a form loads a ListView upload with personel objects. I want to do it when a user double-clicks on a ListView, gets the personel object from the ListView.SelectedItem property and opens a new form and transfers this object to the newly opened form.

Here are my codes for loading Personel objects into a ListView:

public static void GetAll(ListView list)
{
    list.Items.Clear();
    using (FirebirdEntityz context = new FirebirdEntityz())
    {
        ObjectQuery<PERSONEL> query = context.PERSONEL;
        foreach (var item in query)
        {
            var mylist = new ListViewItem { Text = item.NAME };
            mylist.SubItems.Add(item.SURNAME);
            mylist.Tag = item;
            list.Items.Add(mylist);
        }
    }
}

private void Form1_Load(object sender, EventArgs e)
{                     
    GetAll(listView1);
}

This is my personal object for transmitting:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    PERSONEL personel = (PERSONEL)listView1.SelectedItems[0].Tag;
}
-1
source share
4 answers

In the new form to be opened, add the new property to the form class;

private PERSONNEL Personnel{get; set;}
public ShowPersonnel(PERSONNEL _personnel){
   this.Personnel = _personnel;
   //do whatever you want here
}

In basic form

private void listView1_SelectedIndexChanged(object sender, EventArgs e){
        PERSONNEL personnel = listView1.SelectedItems[0].Tag as PERSONNEL;
        Form2 form2 = new Form2();
        form2.ShowPersonnel(personnel);
        form2.Show();

}

May include typos. CHANGE PERSONNEL to staff.

+2
source

, PERSONEL , SelectedIndexChanged. , , PERSONEL.

+3
  • - Factor Mystic.
  • ctor Personnel. , Visual .
+1

. for, - :

list.DisplayMember = "Name"

.

list.DataSource = query.ToList()

, ...

MessageBox.Show(((PERSONEL)list.SelectedItem).Name);

Here's how it works in .net 2.0. But I'm sure there may be a way to do this in 3.0 and above ...

0
source

Source: https://habr.com/ru/post/1722894/


All Articles