Thursday, 16 June 2016

c# event


//form1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace inventory1
{
    public partial class Form1 : Form
    {
        storage y;

        public Form1()
        {
            InitializeComponent();

            y = new storage();

            //raise event my_alert_delegate != null otherwise my_alert_delegate == null
            y.my_alert_delegate +=y_x;
        }

        private void y_x(object sender, alert_args e)
        {
            MessageBox.Show(" low level " + e.quantity.ToString());
        }      


        private void button1_Click(object sender, EventArgs e)
        {
            y.decrease();
            textBox1.Text = y.quantity.ToString();
            y.check_quantity();
        }


    }
}

--------------------------------------------------------------------------
//storage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace inventory1
{
    public class storage
    {      

        public int quantity { get; set; }

        public delegate void alert_delegate(object sender, alert_args e);

        public event alert_delegate my_alert_delegate;

        public storage()
        {
            quantity = 10;
        }

        public storage(int a)
        {
            quantity = a;
        }

        public void check_quantity()
        {
            if (quantity < 5)
            {
                if (my_alert_delegate != null)
                {
                    my_alert_delegate.Invoke(this, new alert_args { quantity = this.quantity });
                }
               
            }          
        }

        public void decrease()
        {
            quantity--;
        }
    }
}

-----------------------------------------------------------------------------
//alert_args.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace inventory1
{
    public class alert_args : EventArgs
    {
        public int quantity { get; set; }
    }
}

No comments:

Post a Comment