İlginizi Çekebilir
  1. Ana Sayfa
  2. C Sharp

C# Event Kavramı

C# Event Kavramı
+ - 2

C# Event Kavramı ile c sharp eğitimlerimize devam ediyoruz. Event kelimesinin Türkçe karşılığı Olay ‘dır. Tabi bu anlamı programlama için geçerlidir. Normal hayatta event kelimesinin anlamı etkinlik ‘tir. Ama biz programcılar için olay ‘dır. Peki bu c sharp event kavramı dediğimiz şey nedir? Daha çok görsel programlamada kullandığımız event kelimesi bir nesnenin özellikleri diyebiliriz. Mesela bir butonun click (tıklama) eventi. Yada form ‘un load eventi, closing eventi gibi.

Konumuz visual studio üzerinden ilerlediğinden önceki derslerimde olduğu gibi visual studio ile anlatımlarımı yapacağım.

C Sharp Event Kavramı

  1. Her nesnenin mutlaka eventleri vardır. (textbox, button, form, gridview vs.)
  2. Bir nesne için tanımlanan bir event, aynı türde başka bir nesne içinde kullanılabilir.
  3. Visual Studio için, her nesnenin varsayılan bir eventi vardır. (Nesneye çift tıkladığınızda otomatik oluşur.)
  4. Farklı türlerde eventler bulunmaktadır. ( EventArgs, KeyEventArgs, MouseEventArgs gibi…)

İlk maddeden açıklamaya başlayalım.

1 – Her nesnenin mutlaka eventi vardır dedik. Mesela textboxlar için textchanged eventi , leave eventi gibi. Bu eventleri mutlaka bilmeli ve kullanmalıyız. Çünkü öyle zamanlar geliyor ki bu eventler ile birkaç satırda yapacağınız işi eventi bilmediğimiz için dünya kadar kod yazmak zorunda kalıyoruz.

2 – Diyelim ki formunuzda 10 adet textbox var. Bir textboxa yazı yazıldığında databaseden bir sorgu çalıştırıp atıyorum aradığınız ürün var mı yok mu kontrol edeceksiniz ve bir labele de bu adetleri yazdıracaksınız. Normal şartlarda 10 tane textchanged eventi olması lazım değil mi? Ancak burada bir event hazırlayıp tüm textboxlara bu eventi atayabiliriz. Örnek olarak bir çalışma hazırladım.

Ekran görüntüsü

c# event kullanımı

 

Kodlar ( Form3.cs)

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 mustafabukulmez_com
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        private void Form3_Load(object sender, EventArgs e)
        {

        }

        private void txtAra_TextChanged(object sender, EventArgs e)
        {
            TextBox txt = sender as TextBox;
            // işlem yapılan textbox'u bu şekilde buluyoruz.

            int adet = 0;
            string AranacaKelime = txt.Text;
            // hangi textbox'a yazı yazıldıysa o yazıyı alıyoruz.

            // sorgu cümleniz... 
            // örnek olsun diye sonuç 10 döndü diyelim.

            adet = 10;
            label1.Text = txt.Text + " aramasından toplam " + adet.ToString() +" adet sonuç bulundu.";
        }


    }
}

 

Nesnelerin bilgilerinin tutulduğu designer.cs dosyası

namespace mustafabukulmez_com
{
    partial class Form3
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.textBox4 = new System.Windows.Forms.TextBox();
            this.textBox5 = new System.Windows.Forms.TextBox();
            this.textBox6 = new System.Windows.Forms.TextBox();
            this.textBox7 = new System.Windows.Forms.TextBox();
            this.textBox8 = new System.Windows.Forms.TextBox();
            this.textBox9 = new System.Windows.Forms.TextBox();
            this.textBox10 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(26, 59);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(211, 22);
            this.textBox1.TabIndex = 0;
            this.textBox1.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(26, 87);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(211, 22);
            this.textBox2.TabIndex = 1;
            this.textBox2.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox3
            // 
            this.textBox3.Location = new System.Drawing.Point(26, 143);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(211, 22);
            this.textBox3.TabIndex = 3;
            this.textBox3.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox4
            // 
            this.textBox4.Location = new System.Drawing.Point(26, 115);
            this.textBox4.Name = "textBox4";
            this.textBox4.Size = new System.Drawing.Size(211, 22);
            this.textBox4.TabIndex = 2;
            this.textBox4.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox5
            // 
            this.textBox5.Location = new System.Drawing.Point(26, 255);
            this.textBox5.Name = "textBox5";
            this.textBox5.Size = new System.Drawing.Size(211, 22);
            this.textBox5.TabIndex = 7;
            this.textBox5.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox6
            // 
            this.textBox6.Location = new System.Drawing.Point(26, 227);
            this.textBox6.Name = "textBox6";
            this.textBox6.Size = new System.Drawing.Size(211, 22);
            this.textBox6.TabIndex = 6;
            this.textBox6.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox7
            // 
            this.textBox7.Location = new System.Drawing.Point(26, 199);
            this.textBox7.Name = "textBox7";
            this.textBox7.Size = new System.Drawing.Size(211, 22);
            this.textBox7.TabIndex = 5;
            this.textBox7.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox8
            // 
            this.textBox8.Location = new System.Drawing.Point(26, 171);
            this.textBox8.Name = "textBox8";
            this.textBox8.Size = new System.Drawing.Size(211, 22);
            this.textBox8.TabIndex = 4;
            this.textBox8.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox9
            // 
            this.textBox9.Location = new System.Drawing.Point(26, 311);
            this.textBox9.Name = "textBox9";
            this.textBox9.Size = new System.Drawing.Size(211, 22);
            this.textBox9.TabIndex = 9;
            this.textBox9.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // textBox10
            // 
            this.textBox10.Location = new System.Drawing.Point(26, 283);
            this.textBox10.Name = "textBox10";
            this.textBox10.Size = new System.Drawing.Size(211, 22);
            this.textBox10.TabIndex = 8;
            this.textBox10.TextChanged += new System.EventHandler(this.txtAra_TextChanged);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(23, 22);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(46, 17);
            this.label1.TabIndex = 10;
            this.label1.Text = "label1";
            // 
            // Form3
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(426, 359);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox9);
            this.Controls.Add(this.textBox10);
            this.Controls.Add(this.textBox5);
            this.Controls.Add(this.textBox6);
            this.Controls.Add(this.textBox7);
            this.Controls.Add(this.textBox8);
            this.Controls.Add(this.textBox3);
            this.Controls.Add(this.textBox4);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Name = "Form3";
            this.Text = "Form3";
            this.Load += new System.EventHandler(this.Form3_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.TextBox textBox3;
        private System.Windows.Forms.TextBox textBox4;
        private System.Windows.Forms.TextBox textBox5;
        private System.Windows.Forms.TextBox textBox6;
        private System.Windows.Forms.TextBox textBox7;
        private System.Windows.Forms.TextBox textBox8;
        private System.Windows.Forms.TextBox textBox9;
        private System.Windows.Forms.TextBox textBox10;
        private System.Windows.Forms.Label label1;
    }
}

Yukarıdaki kodlarda gördüğünüz gibi bir event hazırladık ve 10 textboxa atamasını yaptık. Şimdi düşünün 10 farklı eventimiz olsaydı ve bir değişiklik yapmamız gerekseydi; Bu hali ile ne kadar uğraşacaktık, 10 adet event olsaydı ne kadar uğraşacaktık?.

TextChanged eventi, textboxa yazdığınız her karakter için işlem yapar. Verdiğimiz örnekten yola çıkalım. Yazdığımız kelimeleri database’den arama yapacak dedik. Burada textboxa “m” yazdık gitti db ye “m” ile başlayanları saydı. “mu” yazdık “mu” ile başlayanları saydı. Girilen her karakter için bir işlem yapacak demektir.

 

3 –  Her nesnenin varsayılan bir eventi olur dedik. Örnek olarak;

C# event oluşturma işlemi için nesneleriz üzerinde çift tıklamamız gerekir.

Form’a çift tık yaparsanız “LOAD” eventi oluşur.

TextBox’a çift tıklarsanız “TEXTCHANGED” eventi oluşur.

Button’a çift tıklarsanız “CLICK” eventi oluşur.

GroupBox’a çift tıklarsanız “PAINT” eventi oluşur gibi…

 

4 – Farklı türlerde eventler var dedik. Onlarında birkaçını görelim.

C# Events

        private void Form3_Load(object sender, EventArgs e) { }
        private void Form3_ChangeUICues(object sender, UICuesEventArgs e) { }
        private void Form3_KeyDown(object sender, KeyEventArgs e) { }
        private void Form3_MouseClick(object sender, MouseEventArgs e) { }
        private void Form3_DragDrop(object sender, DragEventArgs e) { }

Yukarıda gördüğünüz kodlarda olduğu gibi farklı event türleri vardır ve bazı işlemleri sadece bu eventler üzerinden yapabilirsiniz. Mesela, CTRL + H yapıldığında bir işlem yaptırmak istiyorsanız “KeyEventArgs” kullanmalısınız. Yani, Form’un KeyDown eventini kullanmak zorundasınız.

 

Gördüğünüz gibi C sharp event kavramı konusu aslında zor bir konu değil. Nesne üzerinde sağ tık yapıp özellikler sayfasını açtığınızda;

c# event oluşturma

görselde oklar ile gösterilen alana tıkladığınızda eventler sayfası açılır ve nesne ile ilgili tüm eventler bu sayfada yer alır. Size lazım olan event adının yanında boş alana çift tık yaptığınızda event otomatik oluşur ve sizi kod sayfasına yönlendirir.

 

Hemen hemen tüm projelerde kullanabileceğiniz bir kaç örnek vereyim. C# event exapmle

1 – Formun kapanmasnı engelleme… 

Bu örneğin en ayrıntılı haline bu linke tıklayarak ulaşabilirsiniz.

 

2 – Kullanıcı programı kapattığında programdan çıkış yaptığını bir db ye yazalım.

<strong>        private void Form3_FormClosing(object sender, FormClosingEventArgs e)</strong>
        {           
            // kullanıcılar tablonuza kul_sistemde diye bir kolon açın ve türünü de bit yapın
            // bu evetn içerisinde de o hücreyi 0 olarak update edin
            // sistemde olan kullanıcıları görmek istediğinizde select sorguna where şartı olarak ekleyebilirsiniz.

            if (MessageBox.Show("Çıkış yapmak istediğinizden emin misiniz?", "Onay Verin", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                // db update işlemleri
                Application.Exit();
                // Burada Close(); da kullanabilirdik ancak, program arka planda çalışmaya devam edeceğinden
                // tüm programı kapatmasını söyledik.
            }
            else
            {
                e.Cancel = true; // (e = form kapanacak | cancal = vazgeç) | true = evet;
                // örnek olarak "e.cancel" form closing eventine ait bir koddur.
                // eventimiz FormClosingEventArgs ve bu eventler ile ilgili işlemleri
                // FormClosingEventArgs 'ı tanımlayan e harfi ile yapıyoruz.
            }
        }

 


C sharp event kavramı dersimiz de bu şekildedir dostlar. C sharp event kavramı hakkında aklınıza takılan soruları sormaktan çekinmeyin. Örnekler konusunda aklıma bir şey gelmediğinden benzer örnekler yazdım. :/

C Sharp Eğitim Seti ve ERP Programlama ders listesi için tıklayınız.

Her zaman olduğu gibi en ayrıntılı bilgiye Microsoft’un sitesinden ulaşabilirsiniz. Olaylar Oluşturma ve İşleme  , Event (C# Başvurusu)

Takipte ve sağlıcakla kalınız. ;)

Bu yazıya tepkiniz ne oldu?

Yazar Hakkında

Lise Ağ Sistemleri ve Yönetimi bölümü, üniversite Bilgisayar Programcılığı bölümü Ön Lisans, Yönetim Bilişim Sistemleri Lisans öğrenimi aldım. Askerlik görevimi tamamladım. Uzmanlık alanım; C# ve SQL Programlama dilleri ile müşteri odaklı, kullanıcı dostu ERP ve CRM gibi sistemleri geliştirmektir. Ayrıca şuanda PHP ve MYSQL alanında projeler geliştirmekteyim. C++, Phyton, Xamarin, MVC gibi konuları öğrenmek ve kendimi geliştirme çabası içerisindeyim. Discord için: https://discord.gg/FBxZeHu9

Değerli yorumlarınızı bekliyorum. :)

Yorumlar (2)

  1. 9 ay önce

    Merhabalar, form kapatma event’nda bir hata var. X ‘e bastığınızda kod kapatılsın mı diye soruyor. Evete tıkladığınızda tekrar soruyor. Hayır desenizde formu kapatıyor.

Bir cevap yazın

E-posta hesabınız yayımlanmayacak.