简体   繁体   中英

C# -Event Handler -Passing value from one form to another

I am developing window application POS. Requirement is: when user click on button 'seach item' on _mainform(form 1) then it open _Searchform(form2) and on the search form it display result in listview with select item button on form3 and close _searchform(form2) . The item that we selected from listview , we add in _mainform(form1) listview .

I try to implement this functionality with delegate and event. On form3 (search result form) i have declared delegate and event and subscribe that even on form1(main form). but when i run application event on form 1 dot get fired.

following this code:

 _mainform(form1):

        namespace KasseDelegate
{

    public delegate void ListViewUpdatedEventHandler(object sender, ListViewUpdatedEventArgs e);
    public partial class Form1 : Form
    {
        private Form3 frm3;

        public Form1()
        {
            InitializeComponent();
            frm3 = new Form3();
            frm3.ListViewUpdated += new ListViewUpdatedEventHandler(Frm3_ListViewUpdated1);

        }

        private void Frm3_ListViewUpdated1(object sender, ListViewUpdatedEventArgs e)
        {
            MessageBox.Show("hi");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.Show();

        }

    }
}



_searchform(form2) :




  public partial class Form2 : Form
        {

            public Form2()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                using (SQLiteConnection con = new SQLiteConnection(Properties.Settings.Default.ConnectionString))
                {
                    con.Open();
                    SQLiteCommand cmd = new SQLiteCommand("select * from varer where varenummer=@Varenummer", con);
                    cmd.Parameters.AddWithValue("@Varenummer", "101");

                    SQLiteDataReader dr = cmd.ExecuteReader();
                    Form3 frm3 = new Form3(dr);                            
                    frm3.Show();
                }
            }
        }

form 3:

namespace KasseDelegate
{

    public partial class Form3 : Form
    {
        public event ListViewUpdatedEventHandler ListViewUpdated;
        SQLiteDataReader dr1;
        public Form3()
        {
            InitializeComponent();

        }
        public Form3(SQLiteDataReader dr)
        {
            InitializeComponent();
            dr1 = dr;
        }

        private void Form3_Load(object sender, System.EventArgs e)
        {
            if (dr1 != null)
            {

                while (dr1.Read() == true)
                {
                    ListViewItem LVI = new ListViewItem();
                    LVI.SubItems.Add(dr1[0].ToString());
                    LVI.SubItems.Add(dr1[1].ToString());
                    LVI.SubItems.Add(dr1[2].ToString());
                    LVI.SubItems.Add(dr1[3].ToString());
                    LVI.SubItems.Add(dr1[4].ToString());
                    listView1.Items.Add(LVI);

                }
            }



        }

        private void button2_Click(object sender, System.EventArgs e)
        {



            string sVareNummer = listView1.SelectedItems[0].SubItems[1].Text;
            string sBeskrivelse = listView1.SelectedItems[0].SubItems[2].Text;
            string pris = listView1.SelectedItems[0].SubItems[4].Text;
            string enpris = listView1.SelectedItems[0].SubItems[5].Text;
            if (ListViewUpdated != null)
            {
                ListViewUpdated(this, new ListViewUpdatedEventArgs() { VareNummer1 = sVareNummer, Beskrivelse1 = sBeskrivelse, Pris1 = pris, Enpris1 = enpris });
            }


        }
    }
    public class ListViewUpdatedEventArgs : System.EventArgs
    {
        private string VareNummer;
        private string Beskrivelse;
        private string pris;
        private string enpris;
        public string VareNummer1
        {
            get
            {
                return VareNummer;
            }
            set
            {
                VareNummer = value;
            }
        }
        public string Beskrivelse1
        {
            get
            {
                return Beskrivelse;
            }
            set
            {
                Beskrivelse = value;
            }
        }
        public string Pris1
        {
            get
            {
                return pris;
            }
            set
            {
                pris = value;
            }

        }

        public string Enpris1
        {
            get
            {
                return enpris;
            }
            set
            {
                enpris = value;
            }

        }
    }
}

So how i can get values of listview selected item from form3(displayitem) to form1.(mainform).

If I understand it correctly you have Form1 - which launches Form2 which in turn launches Form3 . On selecting some item on Form3 you need to update it back on Form1 .

So declare a delegate on Form1 . Pass this delegate to Form2 [ Form2 constructor should accept this as a default parameter - so that if Form2 is triggered from some other place we need not have hard dependency on delegate.]

maintain a private variable of this delegate type on Form2 and while launching Form3 pass the same delegate to Form3 constructor.

On Form3 you have the delegate now which is holding a reference to a method on From1 , so whenever an item is selected you can assign this delegate on Form3 which will fire the method on Form1 .

so here is an working example.

 public delegate void MyDelegate(string selectedItem);
public class Form1
{
    private MyDelegate delegate1;

    public Form1()
    {
         delegate1 = new MyDelegate(ShowSelectedItem);
         var form2 = new Form2(delegate1);
    }

    public void LaunchForm2()
    {

    }

    private void ShowSelectedItem(string result)
    {

    }
}

public class Form2
{
    private MyDelegate form2Delegate;

    public Form2(MyDelegate del = null)
    {
        form2Delegate = del;
        var form3 = new Form3(form2Delegate);
    }

    public void LaunchForm3()
    {

    }


}

public class Form3
{
    private MyDelegate form3Delegate;

    public Form3(MyDelegate del = null)
    {
        form3Delegate = del;
        SelectedItemTriggered("tes");
    }

    public void SelectedItemTriggered(string selectedItem)
    {
        form3Delegate(selectedItem);
        //This will trigger method ShowSelectedItem of Form1

    }


}

You could set up an event in your Form3 and access it from outside like this:

public partial class Form2 : Form
{
    public Form2()
    {
        Form3 new3 = new Form3();
        // Access the event of form3 from outsite
        new3.DisplayedItemChanged += ItemChanged;
    }

    public void ItemChanged(object sender, EventArgs e)
    {
        // This will be triggered.
    }
}

public class Form3 : Form
{
    // Create an event
    public event EventHandler DisplayedItemChanged;

    public void button1_Click(object sender, EventArgs e)
    {
        if (this.DisplayedItemChanged != null)
        {
            // Raise the event and pass any object
            this.DisplayedItemChanged(yourObjectToPass, e);
        }
    }
}

According your comments below:

public partial class Form1 : Form
{
    public Form1()
    {
        // This one is an instance of Form3
        Form3 newForm = new Form3();
        newForm.SomethingHappens += RaiseHere;
    }

    public void RaiseHere(object sender, EventArgs e)
    {
        // Do something...
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        // This one is NOT the same as on Form1. Its a NEW form.
        Form3 newForm = new Form3();
        newForm.Show();
    }
}

public partial class Form3 : Form
{
    public event EventHandler SomethingHappens;

    public Form3()
    {
        //...
    }
}

This wont work, never. You have to use the same instance:

Form3 newForm = new Form3();
newForm.SomethingHappens += RaiseHere;
newForm.Show();

If this isnt clear for you I cant help, sorry:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM