C# ÖRNEKLERİ www.yazilimbilisim.net
İçindekiler C# Dik Üçgende Hipotenüs Hesaplama... 2 C# DataGridView e Resim Ekleme... 3 C# Class Kullanarak Dik Üçgende Hipotenüs Hesaplama... 4 C# WPF Form Binary Saat Uygulaması... 6 C# Veritabanı Müşteri Bakiye ve Tahsilat İşlemleri... 12
C# Dik Üçgende Hipotenüs Hesaplama C#Windows Form kullanarak dik kenarları girilen bir dik üçgene ait Hipotenüs hesabı yapan program örneği: 1 2 3 4 5 6 7 8 private void button1_click(object sender, EventArgs e) double kenar1, kenar2, sonuc; kenar1 = Convert.ToSingle(textBox1.Text); kenar2 = Convert.ToSingle(textBox2.Text); sonuc=math.sqrt((math.pow(kenar1,2)+math.pow(kenar2,2))); label3.text = sonuc.tostring();
C# DataGridView e Resim Ekleme C# Datagridview kontrolüne dinamik olarak sütunlar ekleyip bu sütunlara ait özelliklerin nasıl ayarlanabileceğini vedatagridview kontrolünde istenilen bir sütunaresim ekleme işleminiyapan bir örnek oluşturacağız. Örneğimizi oluşturmaya başlayalım. Öncelikle Yeni bir Windows Form Application projesi açarak içine bir adet DatagridView kontrolü ekliyoruz.datagridview alanlarını ve bu alanlara kayıt ekleme işlemlerini Form_Load olayında aşağıdaki şekilde gerçekleştiriyoruz. private void Form1_Load(object sender, EventArgs e) //Sütunları oluşturuyoruz. DataGridViewTextBoxColumn ad = new DataGridViewTextBoxColumn(); DataGridViewTextBoxColumn soyad = new DataGridViewTextBoxColumn(); DataGridViewImageColumn resim = new DataGridViewImageColumn(); //Datagride alanlarımızı ekliyoruz. datagridview1.columns.add(ad); datagridview1.columns.add(soyad); datagridview1.columns.add(resim); //Sütun başlıklarını ayarlıyoruz. ad.headertext = "ADI"; soyad.headertext = "SOYADI"; resim.headertext = "RESİM"; //Sütun genişliklerini ayarlıyoruz. ad.width = 120; soyad.width = 150; resim.width = 150; //Kayıt girişini gerçekleştiriyoruz. datagridview1.rows[0].cells[0].value = "Ahmet"; datagridview1.rows[0].cells[1].value = "Cansever"; datagridview1.rows[0].cells[2].value = Image.FromFile("yazilimbilsim.jpg");
C# Class Kullanarak Dik Üçgende Hipotenüs Hesaplama C# Windows Form da Class kullanarak Kenarları girilen dik üçgene ait Hipotenüsünü ve Alanını Hesaplayan Örnek: Örneğimizi Property kullanarak oluşturacağız. Girilen kenarın 0 ve daha küçük olması durumunda Classiçerisinde 1 değerine set edilmesini sağlayacağız. Örneğimize başlayalım. İlk olarak Solution Explorer penceresini kullanarak Ucgen.cs isminde Class oluşturuyoruz ve aşağıdaki kodları yazıyoruz. Ucgen.cs kodlarımız: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassUcgen class Ucgen double kenar1; public double Kenar1 get return kenar1; set if (value <= 0) // Kenar 0 ve daha küçükse 1 yapıyoruz. kenar1 = 1; else kenar1 = value; double kenar2;
public double Kenar2 get return kenar2; set if(value<=0) // Kenar 0 ve daha küçükse 1 yapıyoruz. kenar2 = 1; else kenar2 = value; public double Alan() double ucgenalan=0; ucgenalan=(kenar1*kenar2)/2; return ucgenalan; public double Hipotenus() double ucgenhipotenus = 0; ucgenhipotenus = Math.Sqrt((Math.Pow(kenar1, 2) + Math.Pow(kenar2, 2))); return ucgenhipotenus; Form1.cs kodlarımız aşağıdaki gibi olacaktır. private void button1_click(object sender, EventArgs e) Ucgen dikucgen = new Ucgen(); dikucgen.kenar1 = Convert.ToDouble(textBox1.Text); dikucgen.kenar2 = Convert.ToDouble(textBox2.Text); label3.text = "Alan = " + dikucgen.alan(); label4.text = "Hipotenüs = " + dikucgen.hipotenus();
C# WPF Form Binary Saat Uygulaması <Window x:class="binclockc.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="218.492" Width="505.325" Loaded="Window_Loaded" Name="MainWin" WindowStyle="ThreeDBorderWindow" ResizeMode="NoResize"> <Window.Background> <GradientStop Color="Black" Offset="0"/> <GradientStop Color="#FF474747" Offset="1"/> </Window.Background> <Grid x:name="maingrid"> <Rectangle x:name="h0" HorizontalAlignment="Left" Height="35" Margin="211,40,0,0" Stroke="#FF033805" <Rectangle x:name="h1" HorizontalAlignment="Left" Height="35" Margin="254,40,0,0" Stroke="#FF033805"
<Rectangle x:name="h2" HorizontalAlignment="Left" Height="35" Margin="297,40,0,0" Stroke="#FF033805" <Rectangle x:name="h3" HorizontalAlignment="Left" Height="35" Margin="340,40,0,0" Stroke="#FF033805" <Rectangle x:name="h4" HorizontalAlignment="Left" Height="35" Margin="383,40,0,0" Stroke="#FF033805" <Rectangle x:name="h5" HorizontalAlignment="Left" Height="35" Margin="426,40,0,0" Stroke="#FF033805" <Rectangle x:name="m0" HorizontalAlignment="Left" Height="35" Margin="211,83,0,0" Stroke="#FF033805" <Rectangle x:name="m1" HorizontalAlignment="Left" Height="35" Margin="254,83,0,0" Stroke="#FF033805"
<Rectangle x:name="m2" HorizontalAlignment="Left" Height="35" Margin="297,83,0,0" Stroke="#FF033805" <Rectangle x:name="m3" HorizontalAlignment="Left" Height="35" Margin="340,83,0,0" Stroke="#FF033805" <Rectangle x:name="m4" HorizontalAlignment="Left" Height="35" Margin="383,83,0,0" Stroke="#FF033805" <Rectangle x:name="m5" HorizontalAlignment="Left" Height="35" Margin="426,83,0,0" Stroke="#FF033805" <Rectangle x:name="s0" HorizontalAlignment="Left" Height="35" Margin="211,126,0,0" Stroke="#FF033805" <Rectangle x:name="s1" HorizontalAlignment="Left" Height="35" Margin="254,126,0,0" Stroke="#FF033805"
<Rectangle x:name="s2" HorizontalAlignment="Left" Height="35" Margin="297,126,0,0" Stroke="#FF033805" <Rectangle x:name="s3" HorizontalAlignment="Left" Height="35" Margin="340,126,0,0" Stroke="#FF033805" <Rectangle x:name="s4" HorizontalAlignment="Left" Height="35" Margin="383,126,0,0" Stroke="#FF033805" <Rectangle x:name="s5" HorizontalAlignment="Left" Height="35" Margin="426,126,0,0" Stroke="#FF033805" <Label Content="Saat" HorizontalAlignment="Left" Height="35" Margin="10,40,0,0" VerticalAlignment="Top" Width="98" Foreground="White"/> <Label Content="Dakika" HorizontalAlignment="Left" Height="35" Margin="10,83,0,0" VerticalAlignment="Top" Width="98" Foreground="White"/> <Label Content="Saniye" HorizontalAlignment="Left" Height="35" Margin="10,126,0,0" VerticalAlignment="Top" Width="98" Foreground="White"/> <Label Content="Binary Clock" HorizontalAlignment="Left" Height="40" Margin="10,0,0,0" VerticalAlignment="Top" Width="150" Foreground="#FF1BB614" FontSize="18" FontWeight="Bold"/>
<Label Content="1" HorizontalAlignment="Left" Height="26" Margin="438,18,0,0" VerticalAlignment="Top" Width="35" Foreground="#FFCFCDCD" FontSize="10"/> <Label Content="2" HorizontalAlignment="Left" Height="26" Margin="396,18,0,0" VerticalAlignment="Top" Width="30" Foreground="#FFCFCDCD" FontSize="10"/> <Label Content="4" HorizontalAlignment="Left" Height="26" Margin="353,18,0,0" VerticalAlignment="Top" Width="30" Foreground="#FFCFCDCD" FontSize="10"/> <Label Content="8" HorizontalAlignment="Left" Height="26" Margin="310,18,0,0" VerticalAlignment="Top" Width="30" Foreground="#FFCFCDCD" FontSize="10"/> <Label Content="16" HorizontalAlignment="Left" Height="26" Margin="265,18,0,0" VerticalAlignment="Top" Width="40" Foreground="#FFCFCDCD" FontSize="10"/> <Label Content="32" HorizontalAlignment="Left" Height="26" Margin="220,18,0,0" VerticalAlignment="Top" Width="34" Foreground="#FFCFCDCD" FontSize="10"/> <Label x:name="lbhour" Content="00" HorizontalAlignment="Left" Height="31" Margin="174,40,0,0" VerticalAlignment="Top" Width="32" Foreground="#FFFFF9F9"/> <Label x:name="lbminute" Content="00" HorizontalAlignment="Left" Height="31" Margin="174,83,0,0" VerticalAlignment="Top" Width="32" Foreground="#FFFFF9F9"/> <Label x:name="lbseconds" Content="00" HorizontalAlignment="Left" Height="31" Margin="174,126,0,0" VerticalAlignment="Top" Width="32" Foreground="#FFFFF9F9"/> </Grid> </Window> C# kodları; private void Window_Loaded(object sender, RoutedEventArgs e) // Sets all rectangles opacity to 0.35 foreach (var r in LogicalTreeHelper.GetChildren(MainGrid)) if (r is Rectangle) (r as Rectangle).Fill.Opacity = 0.35; // Start a continuous thread Task.Factory.StartNew(() => // while the thread is running... while (true) //...get the current system time DateTime _now = System.DateTime.Now; // Convert each part of the system time (i.e.: hour, minutes, seconds) to binary, filling with 0s up to a length of 6 char each String _binhour = Convert.ToString(_now.Hour, 2).PadLeft(6, '0'); String _binminute = Convert.ToString(_now.Minute, 2).PadLeft(6, '0'); String _binseconds = Convert.ToString(_now.Second, 2).PadLeft(6, '0'); // For each digit of the binary hour representation try for (int i = 0; i <= _binhour.length - 1; i++) // Dispatcher invoke to refresh the UI, which belongs to the main thread
H0.Dispatcher.Invoke(() => // Update the contents of the labels which use decimal h/m/s representation lbhour.content = _now.hour.tostring("00"); lbminute.content = _now.minute.tostring("00"); lbseconds.content = _now.second.tostring("00"); // Search for a rectangle which name corresponds to the _binhour current char index. // Then, set its opacity to 1 if the current _binhour digit is 1, or to 0.35 otherwise (MainGrid.FindName("H" + i.tostring()) as Rectangle).Fill.Opacity = _binhour.substring(i, 1).CompareTo("1") == 0? 1 : 0.35; (MainGrid.FindName("M" + i.tostring()) as Rectangle).Fill.Opacity = _binminute.substring(i, 1).CompareTo("1") == 0? 1 : 0.35; (MainGrid.FindName("S" + i.tostring()) as Rectangle).Fill.Opacity = _binseconds.substring(i, 1).CompareTo("1") == 0? 1 : 0.35; ); ); catch
C# Veritabanı Müşteri Bakiye ve Tahsilat İşlemleri Öncelikle bu işlemleri gerçekleştirmek üzere Formumuzu aşağıdaki şekilde tasarlıyoruz. Form tasarımını tamaladıktan sonra veritabanımıza geçiyoruz. Örneğimizde dbmusteri.accdb isimli access veritabanını kullanacağız. Veritabanımızı oluşturduktan sonra içine Hesap isimli bir tablo oluşturarak aşağıdaki gibi alanlarını oluşturuyoruz. Tabi siz daha gelişmiş bir tablo tasarımı gerçekleştirebilirsiniz. Tablomuzu oluşturduktan sonra deneme amaçlı bir kaç kayıt girdikten sonra tekrar formumuza dönelim. Formumuzda öncelikle yapılacakların bir özetini geçelim. İlk olarak; using System.Data.OleDb; ekleyerek başlıyoruz.
Daha sonra Doldur() isimli bir metot oluşturacağız.bu metot Hesap tablosundaki tüm verilerin listbox1 e çekilmesini sağlayacak. Form yüklendiğinde yani ilk açıldığında ve Müşteri hesabından para çekildiğinde çalışacağı için bu işlemi metot içinde gerçekleştirip daha sonra çağıracağız. Metodumuzu oluşturmadan önce public olarak; OleDbConnection con= new OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=dbMusteri.accdb"); OleDbCommand cmd; OleDbDataReader dr; tanımlamalarımızı yapıyoruz ve Doldur() metodunu oluşturuyoruz. void Doldur() listbox1.items.clear(); listbox1.items.add("müşteri No\tBakiye"); listbox1.items.add("=========================="); cmd = new OleDbCommand(); con.open(); cmd.connection = con; cmd.commandtext = "Select *From Hesap"; dr = cmd.executereader(); while (dr.read()) listbox1.items.add(dr[0] + "\t\t" + dr[1]); con.close(); Bu işlemi tamamladıktan sonra ikinci bir metot daha oluşturacağız. Bu metodumuzun adı BakiyeGetirolacak. Görevi ise gönderilen müşteri numarasına göre o müşteriye ait bakiye bilgisini geri döndürmek olacak. Bu bilgi bize Müşteriden para çekerken gerekecek. Bu metottan dönen değeri çekilmek istenen tutar ile kıyaslayarak işlemi gerçekleştireceğiz. metodumuz int türünde Müşteri Numarasını parametreolarak almakta ve geriye double türünde bakiye bilgisini döndürmekte. public double BakiyeGetir(int mno) con.open(); double musteribakiye=0;
cmd.commandtext = "Select * From Hesap where musterino="+mno+""; dr = cmd.executereader(); while (dr.read()) musteribakiye =Convert.ToDouble(dr[1]); con.close(); return musteribakiye; Metot tanımlamalarını yaptıktan sonra işlerimizin büyük bölümünü halletmiş oluyoruz. Şimdi Form ilk açıldığında Doldur() metodunu çağırarak listbox ta verilerin listelenmesini sağlayalım. private void Form1_Load(object sender, EventArgs e) Doldur(); Son adıma geçiyoruz. Bu adımda Hesaptan Çek butonu içine yazacağımız kodlar bulunuyor. Kodları yazmadan önce kısaca açıklayalım. Butona basıldığında ilk olarak Müşteri No ve Çekilecek Tutarıdeğişkenlere aktarıyoruz. Daha sonra değişkene aktardığımız int türündeki Müşteri numarasınıbakiyegetir isimli Metoda gönderek O müşteri numarasına ait bakiyenin Hesap tablosundan alınmasını sağlıyoruz. Çekilen tutar eğer veritabanında o müşteriye ait bakiyeden büyükse para çekme işlemini gerçekleştirerek çekilen tutarın bakiyeden düşürülmesini ve tablo üzerinde güncellenmesini sağlıyoruz. Aksi durumda Bakiye Yetersiz mesajı verilmesini gerçekleştiriyoruz. private void button1_click(object sender, EventArgs e) int mno=convert.toint32(textbox1.text); double cekilen=convert.todouble(textbox2.text); double mbakiye = BakiyeGetir(mno); if (mbakiye >= cekilen) con.open(); string sorgu = "Update Hesap Set bakiye=(bakiye-@cekilen) where musterino=@musterino"; cmd = new OleDbCommand(sorgu, con); cmd.parameters.addwithvalue("@cekilen", cekilen); cmd.parameters.addwithvalue("@musterino", Convert.ToInt32(textBox1.Text)); cmd.executenonquery(); con.close(); Doldur(); else MessageBox.Show("Yetersiz Bakiye. Şuanki Bakiyeniz: "+mbakiye.tostring("c2"));
Kodlarımızın tamamlanmış hali aşağıdaki gibi olacaktır. 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; using System.Data.OleDb; namespace MusteriHesap public partial class Form1 : Form OleDbConnection con= new OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=dbMusteri.accdb"); OleDbCommand cmd; OleDbDataReader dr; public Form1() InitializeComponent(); void Doldur() listbox1.items.clear(); listbox1.items.add("müşteri No\tBakiye"); listbox1.items.add("=========================="); cmd = new OleDbCommand(); con.open(); cmd.connection = con; cmd.commandtext = "Select *From Hesap"; dr = cmd.executereader(); while (dr.read()) listbox1.items.add(dr[0] + "\t\t" + dr[1]); con.close(); public double BakiyeGetir(int mno)
con.open(); double musteribakiye = 0; cmd.commandtext = "Select * From Hesap where musterino=" + mno + ""; dr = cmd.executereader(); while (dr.read()) musteribakiye = Convert.ToDouble(dr[1]); con.close(); return musteribakiye; private void Form1_Load(object sender, EventArgs e) Doldur(); private void button1_click(object sender, EventArgs e) int mno=convert.toint32(textbox1.text); double cekilen=convert.todouble(textbox2.text); double mbakiye = BakiyeGetir(mno); if (mbakiye >= cekilen) con.open(); string sorgu = "Update Hesap Set bakiye=(bakiye-@cekilen) where musterino=@musterino"; cmd = new OleDbCommand(sorgu, con); cmd.parameters.addwithvalue("@cekilen", cekilen); cmd.parameters.addwithvalue("@musterino", Convert.ToInt32(textBox1.Text)); cmd.executenonquery(); con.close(); Doldur(); else MessageBox.Show("Yetersiz Bakiye. Şuanki Bakiyeniz: "+mbakiye.tostring("c2"));