Program Çalışması

Transkript

Program Çalışması
Visual Studio 2010 .Net C#
Programa giriş ve Çalıştırma
Program Çalışması
2
Visual Studio 2010 .Net C#
-- Bu exe file her Windows makineda eskiden olduğu gibi çalışmaz. Mutlaka .net yüklü
olmalıdır.
3
Visual Studio 2010 .Net C#
Mesaj Verme (Messagebox.Show) ve kütüphane Ekleme ( using )
1. yöntem:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
//using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show("lutfen isimleri boş bırakmayınız ");
}
}
}
II.Yöntem;
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
4
Visual Studio 2010 .Net C#
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("lutfen isimleri boş bırakmayınız ");
}
}
}
Kodlamada Açıklama Kullanma
•
•
Bir satır : //
Çoklu satır : /*
*/
private void button2_Click(object sender, System.EventArgs e)
{
// mesaj kullanma
/*
***********************************************
********
using ile kutuphane ekleme
******
*********
ve
normal kullanım
******
*/
MessageBox.Show("lutfen isimleri boş bırakmayınız");
}
5
Visual Studio 2010 .Net C#
Kod komutlarını kolay yazma
•
•
Boş satırda control – space
: Bütün kod komutları gelir
Bir iki harf yazıp control – space : Baglantılı kod komutları gelir
•
Bir komut yazdıktan sonra . yazma : Baglantılı diğer komutlar gelir . Penceredeki
komutlara Mouse , ok veya tab tuşu ile gelerek; enter veya tab tuşuna basarız.
Using’siz kullanımda nokta aktif olur.
System.Windows.Forms.MessageBox.Show("faruk");
MessageBox.Show("ahmet");
•
- aktif olur
- aktif olmaz
Komutların ilk harfi küçük yazılmasında : Küçük olarak yazılırsa control-space ile
yinede komutlar gelir. Tab veya Enter yuşu ile ilk harf büyütülmüş hale gelir.
6
Visual Studio 2010 .Net C#
Pencereler
•
•
•
•
•
•
•
Properties : forms,button,texbox gibi objelerin özelliklerini değiştirme
Events
: Mouse’a tıklayınca,uzerine gidince veya enter’a basınca işlem yapma
Toolbox : button, textbox gibi objeleri ekleme
Solution : soluşın,proje ve forms kontrolu
Server Explorer : Sql Server ile baglantı menusu
Task list : Run veya derlemede hatalı satırları görme
Araç Cubukları ( View-Toolbars ile gelir. Standart, Text Editor gibi) : Pencereleri
getirme
7
Visual Studio 2010 .Net C#
Events Kullanma
8
Visual Studio 2010 .Net C#
Form , Code ,Sqlserver baglantı , form butonları penceresini getirme
Yapılmış bir projeye girdiğimizde bu ekranlar gelmeyebilir. Veya biz yanlışlıkla silmiş
olabiliriz.
9
Visual Studio 2010 .Net C#
Program yazma yöntemleri
Textbox bir objenin dış rengini değiştirme
1) Properties penceresinden
2) Kod yazma ile
private void button1_Click(object sender, EventArgs e)
{
textBox1.BackColor = Color.Red;
}
Textbox bir objenin Ekranda gözükmemesi
Kod yazma ile
private void button1_Click(object sender, EventArgs e)
{
textBox1.Visible= false;
}
10
Visual Studio 2010 .Net C#
Değişkenler
Tamsayı Değişkenler
byte
Aldıgı sayı aralığı
0 -
sbyte
-128
short
-32178
ushort
0
int -2147483647
uint
0
255
- +128
- +32178
- 65535
- (+2147483647
- 4294967295
Real Sayı değişkenler
float Normal real sayı tipi
Double Geniş real sayı tipi
Long Çokgeniş sayı tipi
Alfasal değişkenler
string
bool
True ve false tipidir
Açıklama
byte x ;
byte y=100;
sbyte x;
sbyle y= -110;
sbyte x;
sbyle y= -3200;
sbyte x;
sbyle y= 2000;
sbyte x;
sbyle y= -110556;
sbyte x;
sbyle y= 110767;
sbyte x;
sbyle y= 100.25;
sbyte x;
sbyle y= 100.25;
sbyte x;
sbyle y= 100.25;
string adres;
string adi=”Faruk”;
Bool medeni;
Bool erkek=true;
Özellikler
•
Değişkenleri bir veya birden fazla arasına virgül koyarak tanımlayabilir.direk
normal veya sabit giriş yapabilir
•
String degerler cift tırnak arasında yazılır. “ …. “
•
noktalı virgül ile işlem satırın bitişini saglarız. ;
•
deger aktarma delphi de iki nokta ve eşittir ( := ).Burada ise sadece eşittir ( = )
kullanılır.
•
Matematiksel işlemlerde Math.Pow kullanılır.Sayıyı kendisiyle çarpar..
int ucret=10;
MessageBox.Show(Math.Pow(ucret,1).ToString()); // 10
MessageBox.Show(Math.Pow(ucret,2).ToString()); // 100
MessageBox.Show(Math.Pow(ucret,3).ToString()); // 1000
const double pi=3.14; -- sabit tanımlama
int yas=25;
-- direk tanımlayıp giriş
String ulke=”Türkiye” ;
11
Visual Studio 2010 .Net C#
int a;
int b,c;
-- iki değişken tanımlama
string adi,soyad,adres; - iki değişken tanımlama
double net;
Real değişken tanımlama
String t="100";
b=Convert.ToInt32(textBox1.Text);
net=a+Double.Parse(t);
b=a+int.Parse(t);
// standart integer’a cevirme
// real sayı için cevirme
// integer için cevirme
textBox4.Text=a.ToString();
// string’e cevirme
b=Convert.ToDouble(textBox1.Text); // Real Sayıya cevirme
adres=" Kervansaray mah. Dogs evleri E blok";//string deger giriş
12
Visual Studio 2010 .Net C#
Uygulamalar
•
Textbox1.text değişkeni integer’a cevrim yaparak a sayısı ve 5 ile toplama ve toplam
degerin textbox4.text’te yazılması ve mesaj olarak verilmesi.
Đnteger sayının textbox4 ‘te veya messagebox ile yazılması için string’ dönüşmesi
gereklidir.
MessageBox.Show(b.ToString());
Messagebox’ta birden fazla alfasal degişkeni yazdırma için aralarında + kullanılır.
veya string olarak birleştirmek için yine + kullanılır.
Textbox4.Text=adi + “ “+soyad;
private void button1_Click(object sender, System.EventArgs e)
•
{
int a;
int b,c;
a=1000;
b=5+a+Convert.ToInt32(textBox1.Text); // -->integer’a cevirme
textBox4.Text=a.ToString();
// - string’e cevirme
MessageBox.Show(b.ToString());
MessageBox.Show(b.ToString()+" toplam degerdir");
}
Real Sayıya cevirme
private void button2_Click(object sender, System.EventArgs e)
{
int a;
Double b;
a=1000;
b=5+a+Convert.ToDouble(textBox1.Text);//real sayıya cevirme
textBox4.Text=a.ToString();
MessageBox.Show(b.ToString());
MessageBox.Show(b.ToString()+" toplam degerdir");
}
•
String deger giriş,birleştirme,mesaj olarak yazdırm
private void button3_Click(object sender, System.EventArgs e)
{
String adres;
adres=" Kervansaray mah. Dogs evleri E blok no:7";
textBox4.Text=adres+textBox1.Text;
MessageBox.Show(textBox4.Text);
}
•
Tarih formatına ekranda yazdırma
String deger="20/09/2005";
DateTime tarih,tarih2;
tarih=DateTime.Parse(deger); // stringi tarih formatına ceviriyor
tarih2=DateTime.Parse(textBox1.Text);
textBox4.Text=tarih.ToString();
13
Visual Studio 2010 .Net C#
Event , Form ve Formlar arasında Değişken kullanımı
“Bir event içersinde kullanılan değişkenler sadece o event içersinde geçerlidir. bir
değişkeni button1 event’ında, iki değişkeni button2 event’ında kullanılır. Private ile
event’lar dışında tanımladıgımız değişkeni ( fsayi) bir form içersinde her event’ta
kullanabiliriz. Bir form’da kullandığımız değişkenin diğer formlarda kullanmak için
public ile tanımlarız.”
Code kısmı :
private int fsayi=100; // fsayi Bir formun içinde her event'ta kullanılır.
public static int genel=30; // genel bütün formlarda kullanılır
private void button1_Click(object sender, System.EventArgs e)
{
int bir;
fsayi++;
bir=100+fsayi;
MessageBox.Show(bir.ToString());
MessageBox.Show(genel.ToString());
}
private void button2_Click(object sender, System.EventArgs e)
{
int iki;
iki=200+fsayi;
MessageBox.Show(iki.ToString());
MessageBox.Show(genel.ToString());
// MessageBox.Show(bir.ToString()); kullanılamaz. bir değişkeni
button1'dedir.
}
Dizin Kullanımı
private void button8_Click(object sender, System.EventArgs e)
{
// tek boyutlu dizin tanımlama
int[] yas;
yas=new int[10]; // 0 ile 9 arasında 10 dizin oluşur
yas[5]=100;
yas[2]=120;
MessageBox.Show(yas[5].ToString()+"
" + yas[2].ToString());
// 5 elemanlı ulke dizin tanımlama. giriş hemen yapılıyor
String[] ulke;
ulke=new String[5] {"turkiye","almanya","ingiltere","cin","rusya"};
String[] sehir={"denizli",",zmir","ankara"};
MessageBox.Show(sehir[2]+"
"+ ulke[3]);
14
Visual Studio 2010 .Net C#
// 2 boyutlu dizin tanımlama
String[,] adi;
adi=new String[5,7];
adi[1,3]="faruk senturk";
adi[2,4]="ahmet korkmaz";
MessageBox.Show(adi[1,3]+"
" + adi[2,4]);
}
diznin boyutu
: Rank
Diznin elaman sayısı : GetLength
Diznin Üst sınırı
: GetupperBound
int[] yas;
yas=new int[10];
// 0 ile 9 arasında 10 dizin oluşur
MessageBox.Show("boyutu ..:"+yas.Rank.ToString()+"diznin eleman
sayısı..:"+yas.GetLength(0).ToString()+"üst sınır
..:"+yas.GetUpperBound(0).ToString());
Kullanılan Operatörler
Atama
Eşitlik
veya
ve
Değl
Eşit değil
Büyüktür
kücüktür
Büyük eşittir
Küçük eşittir
X++
++X
X---X
X+=5
X-=5
X*=5
=
==
||
&&
!
!=
>
<
>=
<=
X=X+1
X=X+1
X=X-1
X=X-1
X=X-5
X=X-5
X=X*5
A=100;
if(a==100)
İf((a==100)||(b==50))
İf((a==100)&&(b==50))
İf(!(a==100))
İf(a!=10)
İf(a>10)
İf(a<10)
İf(a>=10)
İf(a<=10)
15
Visual Studio 2010 .Net C#
Form ve code Penceresinin Çağrılması
“ Bir c# projesi open edilince code ve form ekranı gelmeyebilir veya yanlışlıkla bu
pencereleri silebiliriz. “
•
•
•
•
Proje open edilir. ( file – project – Windowsapplication5.sln )
Solution Explorer penceresi çağrılır. View -- solution Explorer
Solution Explorer’da form1.cs cift tıklanır. Form1 designer gelir.
Code penceresi cagrılır. View ----- Code
Program çalışmasında değer kontrolü
•
•
•
TextBox veya label alana atma
MessageBox ile ekranda yazdırma
Kod izleme
16
Visual Studio 2010 .Net C#
17
Visual Studio 2010 .Net C#
Hesap makinesı Örnegi
private void comboBox1_SelectedIndexChanged(object sender,
System.EventArgs e)
{
double i;
i=0;
if (comboBox1.Text=="toplama")
{
if ((textBox1.Text != "") && (textBox2.Text != ""))
i = Double.Parse(textBox1.Text) + Double.Parse(textBox2.Text);
}
if (comboBox1.Text=="cıkarma")
{
if ((textBox1.Text != "") && (textBox2.Text != ""))
i = Double.Parse(textBox1.Text) - Double.Parse(textBox2.Text);
}
if (comboBox1.Text=="bolme")
{
if ((textBox1.Text != "") && (textBox2.Text != ""))
i = Double.Parse(textBox1.Text) / Double.Parse(textBox2.Text);
18
Visual Studio 2010 .Net C#
}
if (comboBox1.Text=="carpma")
{
if ((textBox1.Text != "") && (textBox2.Text != ""))
i = Double.Parse(textBox1.Text) * Double.Parse(textBox2.Text);
}
label3.Text=i.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 0; // ilk girilen( toplama gibi) gözükür
}
* double.Parse string degeri integer’a cevirir.
* i.ToString() i ‘nin integer degerini string degerine cevirir.
Yeni form Çağrılması
project --> add windows form ile önceden form2 yaratılmalıdır.
private void button5_Click(object sender, System.EventArgs e)
{
Form2 yeni=new Form2();
yeni.Show();
}
Programdan Çıkış
private void button6_Click(object sender, System.EventArgs e)
{
Application.Exit();
}
Form’dan Çıkış
this.Close();
Makinenın Adını öğrenme
textBox4.Text=System.Security.Principal.WindowsIdentity.GetCurrent().Name;
19
Visual Studio 2010 .Net C#
Değişkenleri Düzenlemek
Procedure ve Fonksiyon
Procedure (dönüşsüz):
private void mesaj(string mes1,string mes2,int gun2)
{
MessageBox.Show(mes1+" "+mes2+" "+gun2.ToString());
}
private void button3_Click(object sender, System.EventArgs e)
{
String adi="Volkan Şentürk";
int yas=10;
mesaj(adi,textBox1.Text,yas);
listBox1.Items.Add(adi+textBox1.Text+yas.ToString());
}
Fonsiyon (dönüşlü):
private static int hesapla(int ucr2,int gun2)
{
int brut=ucr2*ucr2;
//String genadi="okutman"+adi2;
return brut;
}
private void button1_Click(object sender, System.EventArgs e)
{
String adi="Faruk Şentürk";
int ucr=Convert.ToInt32(textBox1.Text); // string int'e cevriliyor
int gun=20;
textBox2.Text=hesapla(ucr,gun).ToString();
}
20
Visual Studio 2010 .Net C#
Struct ve Class Yapılar, Enum Uygulama
Önce groupbox cift tıklama veya sürükleyerek sayfaya getirilir. Radiobutton ise iki kez
sürüklenerek groupbox1 içerisine bırakılır. Daha sonra button çift tıklanarak iki button
oluşturulur.
enum hafta
{
pazartesi = 0,
sali = 1,
carsamba = 2,
persembe = 3,
cuma = 4,
cumartesi = 5,
pazar = 6
}
hafta yeni;
private void gun()
{
if (yeni == hafta.pazartesi)
{
MessageBox.Show("monday");
}
else if (yeni == hafta.sali)
{
MessageBox.Show(this, "tuesday");
}
else if (yeni == hafta.carsamba)
{
MessageBox.Show(this, "wednesday");
}
else if (yeni == hafta.persembe)
{
MessageBox.Show(this, "thursday");
}
else if (yeni == hafta.cuma)
{
MessageBox.Show(this, "friday");
21
Visual Studio 2010 .Net C#
}
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
yeni = hafta.pazartesi;
gun();
}
else
{
yeni = hafta.carsamba;
gun();
}
}
private void button2_Click(object sender, EventArgs e)
{
yeni++;
gun();
}
MessageBox Fonksiyonu
•
•
•
MessageBox.Show("pamukkale üniversitesi");
// pamukkale üniversitesi
MessageBox.Show(this,"pamukkale üniversitesi"); // pamukkale üniversitesi
MessageBox.Show("pamukkale","mesaj penceresi"); // pencere ismi
•
int aa;
String adi="Merve tas";
aa=140;
MessageBox.Show(aa.ToString()); // 140 yazar
MessageBox.Show(adi+" "+aa.ToString()); // merve senturk 140
MessageBox.Show(adi+" "+aa.ToString(),"personel bilgileri"); // ayrıca pencere ismini verir
•
DialogResult devam;
devam=MessageBox.Show("islem devam etsinmi","Muhasebe sistemi",
MessageBoxButtons.YesNoCancel );
if (devam==DialogResult.No)
22
Visual Studio 2010 .Net C#
{
MessageBox.Show("form kapanıyor");
this.Close();
}
else if (devam==DialogResult.Cancel)
{
MessageBox.Show("cıkılıyor");
Application.Exit();
}
else
{
MessageBox.Show("Program calısmaya devam ediyor");
}
•
devam=MessageBox.Show("islem devam etsinmi","Muhasebe
sistemi",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Error);
•
devam=MessageBox.Show("islem devam etsinmi","Muhasebe sistemi",
MessageBoxButtons.YesNoCancel,MessageBoxIcon.Error,MessageBoxDefaultButton.Button2);
•
devam=MessageBox.Show("islem devam etsinmi","Muhasebe
sistemi",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Error,MessageBoxDefaultButton.Button2,
MessageBoxOptions.RightAlign);
MessageBoxButtons.YesNoCancel
MessageBoxButtons YesNoCancel
YesNo
RetryCancel
OKCancel
OK
AbortRetryIgnore
MessageBoxIcon.Asterix
MessageBoxIcon
Asterix
Error
Exclamation
Hand
Information
None
Question
Stop
Warning
23
Visual Studio 2010 .Net C#
InputBox Fonsiyonu
C#’da Visual basic6.0 daki gibi bir bilgi giriş fonksiyonu yoktur. Fakat bu fonsiyonu Visual
Basic’den çağırarak rahatlıkla kullanabiliriz.
•
Visual Basic fonksiyonu çağrılır.
•
InputBox fonksiyonu kullanma
string sifre;
sifre=Microsoft.VisualBasic.Interaction.InputBox("sifreyi giriniz","sifre girisi","pamuk",100,200);
24
Visual Studio 2010 .Net C#
Şartlar
•
•
•
•
•
•
•
•
•
İf
switch
for
while : for döngüsünden farkı kac kez işletilecegi belli degildir.
do-while : while’den farkı şartın döngü dışında kontrol edilmesidir.
foreach
break dongu kontrol metodu
thread.sleep() metodu
application.DoEvents() metodu
İf Yapıları
•
Basit if yapısı :
if(a==20)
{
}
•
if-else yapıları :
if(a==20)
{
}
else
{
}
•
if-else-if-else yapıları :
if(a==20)
{
// a=20 şart gecerli oldugunda çalışacak kod
}
else if(a==30)
{
// a=30 şart gecerli oldugunda çalışacak kod
}
else
{
// üsteki iki kod geçersiz olmasında çalışacak kod
}
25
Visual Studio 2010 .Net C#
Switch Yapısı
int notu;
if (textBox1.Text != "") { notu = Convert.ToInt16(textBox1.Text); }
else notu = 0;
switch (notu)
{
case 10:
label1.Text = "sınavdan on aldınız";
break;
case 20:
label1.Text = "sınavdan yirmi aldınız";
break;
case 30:
label1.Text = "sınavdan otuz aldınız";
break;
case 40:
case 50:
case 60:
case 70:
label1.Text = "sınavdan 40-70 arası aldınız";
break;
default:
label1.Text = "sınava girmediniz";
break;
-- case "istanbul":
string olarak kullanırız.
switch (textBox1.Text)
{
case "rize":
label1.Text
break;
case "ankara":
label1.Text
break;
case "izmir":
case "denizli":
case "usak":
label1.Text
break;
default:
label1.Text
break;
= "karadeniz bölgesindedir";
= "iç anadolu bölgesindedir";
= "ege bölgesindedir";
= "yeniden giriniz";
For yapısı
int k,say=10;
for(k=1;k<10;k++)
// for(k=1;k<=10;k+=2)
{
if(k==5) break;
say+=10;
ikişer ikişer artış
26
Visual Studio 2010 .Net C#
//
}
Form1.ActiveForm.Text=say.ToString();
label1.Text=say.ToString();
formun baslıgında yazma
foreach yapısı
string[] fakulte=new string[3] {"muhendislik","tıp","eğitim"};
foreach(string yaz in fakulte)
{
Form1.ActiveForm.Text=Form1.ActiveForm.Text+" ~~~ "+yaz;
}
---- formun başlıgına, mühendislik~~~ tıp ~~~ eğitim
yazar .
while Yapısı
int k=1,tt=0;
while(k<=10)
{
k++;
tt=tt+10;
}
label1.Text=tt.ToString();
int bb=1,pam=0;
do
{
bb++;
pam+=10;
} while(bb<=5);
label1.Text=pam.ToString();
27
Visual Studio 2010 .Net C#
thread.sleep() ve application.DoEvents() metodu
-- Textbox’a Girdiğimiz ismi listbox ve label’a tek tek yazılması
Hatırlatma:
Threading kütüphanesi eklenmelidir.
using System.Threading;
using System.Threading;
private void button1_Click(object sender, EventArgs e)
{
int k;
for(k=0;k<=textBox1.Text.Length-1;k++)
{
Thread.Sleep(1500); // 1 sn bekle
Application.DoEvents(); // for dongusu, listbox1 ve label1'e atama birlikte
calışşsın.for baglama yapmasın.yani for'n bitmesini beklemesinler
listBox1.Items.Add(textBox1.Text.Substring(k,1));
label1.Text=label1.Text+textBox1.Text.Substring(k,1);
//MessageBox.Show(textBox1.Text.Substring(k,1));
}
28
Visual Studio 2010 .Net C#
Class Yapısı
•
•
Bir form yaratılır ve üzerinde değişkenler oluşturulur.
Project - add class ile class yaratılır ve projeye otomatik dahil olur. Biz üzerinde
gereken düzeltmeleri ve değişken eklemeleri yaparız.
using System;
namespace class_yapı
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class aile
{
public static string adi_soyadi;
public static string adresi;
public static int yasi;
public static bool medeni_hal;
public static string meslegi;
public static long maasi;
public const int sabit=1000;
public static long maashesapla(int katsayi,int kidem)
{
return sabit*katsayi*kidem;
}
}
}
29
Visual Studio 2010 .Net C#
•
Butona( hesapla butonu ) tıklayarak kodlama yapılır.
private void button1_Click(object sender, System.EventArgs e)
{
aile.adi_soyadi=textBox1.Text;
aile.adresi=textBox2.Text;
aile.yasi=Convert.ToInt32(textBox3.Text);
aile.medeni_hal=checkBox1.Checked;
aile.meslegi=comboBox1.Text;
aile.maasi=aile.maashesapla(Convert.ToInt32(textBox5.Text),
Convert.ToInt32(textBox6.Text));
textBox4.Text=aile.maasi.ToString();
MessageBox.Show(aile.yasi.ToString());
}
özellikler
1. aile isminde bir class oluşturuldu
2. button1_click içersinde aile. ( noktaya tıklayınca) bir pencere gelir ve istedimiz
değşkeni seceriz. Class oluşturulurken Değişenleri public static ( her yerde
kullanılsın) tanımladıgımız için gelmektedir. Private tanımlarsak gelmez.O zaman
yavru class oluştururuz.
Private tanımlı class yapısı
•
Project -- add class ile bir class oluşturulur. Taralı alanı faruk class’ı olarak
yazarız.
using System;
namespace class_yapı
{
/// <summary>
/// Summary description for Class2.
/// </summary>
public class faruk
{
private int z=5;
public int hesapla(int kidem)
{
return kidem*z;
}
30
Visual Studio 2010 .Net C#
public faruk()
{
//
// TODO: Add constructor logic here
//
}
}
}
public static (ana class ) ve private ( yavru class ) Kullanımı
Değişkenlerin public static ile tanımlanması :
Bir class tanımlamada değişkenleri public static ile tanımlarsak butun
tanımların içersinde kullanımda class ismini yazıp noktaya basınca
değşkenler pencerede gelir, Secerek kullanmış oluruz.
Class:
public class faruk
{
public static int z=5;
public static int hesapla(int kidem)
{
return kidem*z;
}
Bir buton içersinde class kullanma :
private void button2_Click(object sender, System.EventArgs e)
{
int sonuc;
sonuc=faruk.hesapla(100);
Form1.ActiveForm.Text=sonuc.ToString();
MessageBox.Show(sonuc.ToString());
textBox4.Text=sonuc.ToString();
}
sonuc:
biz buton içersinde kod yazarken faruk. ‘da hesapla değişkenin bulundugu pencere gelir. Biz
hesapla ‘yı seceriz. Class’taki değişkenler public static ile tanımlanmıştır.
sonuc=faruk.hesapla(100);
31
Visual Studio 2010 .Net C#
hesap2 butona( button2_click) tıklayınca formun title’da textbox3.text’te ve messagebox’ta
500 yazar.
Değişkenlerin private ile tanımlanması :
class’ların içersindeki bütün değişkenler public static ile
tanımlanmazlar. O zaman tüm her kodlamada bu değişkenlere kolayca
ulaşabiliriz. Herkesin o değişkenlere ulaşmaması için değişkenleri private
ile tanımlarız.
Buton tanımlamada yavru class yaratarak( merve) merve üzerinden çalışma
yapıyoruz.faruk class’ından / içerinde private ( sadece o class ve form’da
kullan) tanımlanmış. Biz view bir class yaratmış oluyoruz. Merve. Yazınca
değişkenlerin tanımlı oldugu pencere gelir. Faruk.’da gelmez.
Class :
public class faruk
{
private int z=5;
public int hesapla(int kidem)
{
return kidem*z;
}
Bir buton içersinde class kullanma :
private void button2_Click(object sender, System.EventArgs e)
{
int sonuc;
faruk merve=new faruk(); // merve yavru class oluşturma
sonuc=merve.hesapla(100);
Form1.ActiveForm.Text=sonuc.ToString();
MessageBox.Show(sonuc.ToString());
textBox4.Text=sonuc.ToString();
}
32
Visual Studio 2010 .Net C#
sonuc:
aynı şekilde hesap2 butona( button2_click) tıklayınca formun title’da textbox3.text’te ve
messagebox’ta 500 yazar.
Class ‘ta değiştirme
Get ve set komutları vardır. Get’de geriye doönecek deger’i veririz. Set’de değişecek
değişkenin adını yazarız.
Class:
public class degistirme
{
public string memleket;
public string etiket
{
get
{
string yer;
yer="bu arkadas"+memleket+" sehrinde oturmaktadır";
return yer;
}
set
{
memleket=value;
}
// degişecek demektir
}
public degistirme()
{
//
// TODO: Add constructor logic here
//
}
Bir buton içersinde
kullanım :
private void button3_Click(object sender, System.EventArgs e)
{
degistirme yeni=new degistirme();
yeni.memleket="denizli";
MessageBox.Show(yeni.etiket);
}
33
Visual Studio 2010 .Net C#
Class’ta sadece okuma
Class:
public class sadeceokuma
{
public readonly string isim="faruk senturk";
public string oku
{
get
{
return isim;
}
}
Bir buton içersinde
kullanım :
sadeceokuma yeni=new sadeceokuma();
//yeni.isim="merve"; // bu atama hata verir.
MessageBox.Show(yeni.isim);
Class’ta yazma
Class:
public class yaz
{
public string isim="volkan senturk";
public string pamuk
{
set
{
isim=value;
}
}
}
Bir buton içersinde
kullanım :
private void button5_Click(object sender, System.EventArgs e)
{
yaz yeni=new yaz();
yeni.isim="merve";
MessageBox.Show(yeni.isim);
}
34
Visual Studio 2010 .Net C#
Hata Yakalama ( try – catch )
•
•
•
Hata durumunda Bir mesaj ve hata kodu ( try – catch )
Hata durumunda farklı mesajlar ( try – catch – catch – catch )
dogru veya hatalı çalışmasında mutlaka çalışsın (try-catch-finally)
•
Hata durumunda Bir mesaj ve hata kodu
private void button1_Click(object sender, System.EventArgs e)
{
int say1,say2;
double tt;
try
{
say1=Convert.ToInt32(textBox1.Text);
say2=Convert.ToInt32(textBox2.Text);
tt=say1/say2;
label1.Text=tt.ToString();
}
catch( System.Exception hatano )
{
MessageBox.Show("degerleri dogru giriniz");
MessageBox.Show("Hata mesajı ...:"+hatano);
}
}
35
Visual Studio 2010 .Net C#
•
Hata durumunda farklı mesajlar
private void button2_Click(object sender, System.EventArgs e)
{
int say1,say2;
double tt;
try
{
say1=Convert.ToInt32(textBox1.Text);
say2=Convert.ToInt32(textBox2.Text);
tt=say1/say2;
label1.Text=tt.ToString();
}
catch(FormatException hatano)
{
MessageBox.Show("degerlere sayı giriniz");
}
catch(DivideByZeroException hatano)
{
MessageBox.Show("0 'a bolme hatası");
}
catch( System.Exception hatano )
{
MessageBox.Show("degerleri dogru giriniz");
MessageBox.Show("Hata mesajı ...:"+hatano);
}
}
•
dogru veya hatalı çalışmasında mutlaka çalışsın (finally)
private int tam;
private void button3_Click(object sender, System.EventArgs e)
{
int say1,say2;
double tt;
try
{
say1=Convert.ToInt32(textBox1.Text);
say2=Convert.ToInt32(textBox2.Text);
tt=say1/say2;
label1.Text=tt.ToString();
}
catch(FormatException hatano)
{
MessageBox.Show("degerlere sayı giriniz");
}
catch(DivideByZeroException hatano)
{
MessageBox.Show("0 'a bolme hatası");
36
Visual Studio 2010 .Net C#
}
catch( System.Exception hatano )
{
MessageBox.Show("degerleri dogru giriniz");
MessageBox.Show("Hata mesajı ...:"+hatano);
}
finally
{
tam++;
MessageBox.Show(tam.ToString());
}
Fonksiyonlar
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Pozatife cevirme (Abs)
Kusuratı yuvarlama ile cıkarma (Ceiling , Flor)
Ondalık Kısmındaki sayıyı yuvarlama ( Math.Round )
En küçük, En büyuk sayıyı bulma ( Max,Min)
Üslü kuvveti alma ( Math.Pow
karesi,üçlü kuvveti … )
Karekök alma (Math.Sqrt)
Rasgele sayı ( Random )
Değer karşılaştırma ( Compare , Equals )
Dizin elemanları arasına karekter yerleştirme (join )
Uzunluk ( Lenght) , Pozisyon bulma (IndexOf )
Karekter girişi ( Insert)
Karekter Silme ( Remove )
Karekter Değiştirme ( Replace)
Karekter çıkarma ( Substring)
Büyük Harfe çevirme ( ToUpper )
küçük Harfe çevirme ( ToUpper )
Boşluğu cıkarma ( Trim)
Tarih Fonsiyonları
Directory Yaratma ( Create Directory )
Program Listeleme ( directory.GetFiles )
Sürücü Listeleme (Directory.GetLogicalDrives )
Dosya Kopyalama
Dosya Taşıma
Dosya Silme
Dosyanın directory,Uzunluk ve ismi
Yeni Bir Dosya oluşturma
Bir TextBox alanı text dosyaya kayıt etme
Bir Text Dosyayı Listitem’a taşıma
Textbox veya label’a Text dosyadan okuma
37
Visual Studio 2010 .Net C#
•
Pozatife cevirme(Abs)
“ Eksili sayıları artıya çevirir.”
private void button1_Click(object sender, System.EventArgs e)
{
double x;
x=Math.Abs(Convert.ToDouble(textBox1.Text));
label4.Text=x.ToString();
}
•
Kusuratı yuvarlama ile atma(Ceiling,Floor)
private void button2_Click(object sender, System.EventArgs e)
{
double x;
x=Math.Ceiling(Convert.ToDouble(textBox1.Text));
label4.Text=x.ToString();
}
Ceiling: Kusuratlı sayıları kusuratı atarak mutlaka bir büyüge cevirme
negatifli sayıları sadece kusuratını atar.
25 ---> 25
32,60 ---> 33
-32,01 ---> 32
-32,60 ---> -32
Floor: Match.Floor ise tam tersini yapar.
32,01 ---> 33
x=Math.Floor(Convert.ToDouble(textBox1.Text));
25 ---> 25
-32,01 ---> 33
•
32,60 ---> 32
-32,60 ---> -33
32,01 ---> 32
Ondalık Kısmındaki sayıyı yuvarlama ( Math.Round )
Ondalık kısmındaki rakam sayısı.yuvarlama yapar tamsayı ise aynen alır.
100---> 100
25,45678 ---> 25.46
25.45478 ---> 25.45
private void button5_Click(object sender, System.EventArgs e)
{
double x;
x=Math.Round(Convert.ToDouble(textBox1.Text),2);
label4.Text=x.ToString();
}
•
En küçük, En büyük sayıyı bulma ( max,min)
private void button3_Click(object sender, System.EventArgs e)
{
// İki sayıdan büyügünü alma
double x;
x=Math.Max(300,200); // 300 alır
label4.Text=x.ToString();
// İki sayıdan küçüğünü alma
38
Visual Studio 2010 .Net C#
x=Math.Min(300,200); // 200 alır
label5.Text=x.ToString();
}
•
Üslü kuvveti alma ( Math.Pow
karesi,uclu kuvveti … )
private void button4_Click(object sender, System.EventArgs e)
{
// Convert.Todouble sayısala cevirmeyi yapar
double x;
x=Math.Pow(Convert.ToDouble(textBox1.Text),2); // karesini alır
label4.Text=x.ToString();
x=Math.Pow(Convert.ToDouble(textBox1.Text),3); // uclu kuvvetini alır
label5.Text=x.ToString();
•
Karakök alma
private void button6_Click(object sender, System.EventArgs e)
{
double x;
x=Math.Sqrt(100); // 10 yazar
label4.Text=x.ToString();
}
•
Rasgele sayı ( Random )
private void button7_Click(object sender, System.EventArgs e)
{
// Normal rasgele farklı sayı
int say;
Random rasgel=new Random();
say=rasgel.Next()%20; // 0- 20 arası sayı uretilir
label4.Text=say.ToString(); // 3
say=rasgel.Next()%20;
label5.Text=say.ToString(); // 14
// Saatin salisinden faydalanarak her seferinde farklı sayı
// butona tıklayınca mutlaka farklı sayı
int say;
DateTime zaman=DateTime.Now;
Random rasgel=new Random( (int)zaman.Millisecond );
say=rasgel.Next()%20;
label4.Text=say.ToString();
say=rasgel.Next()%20;
label5.Text=say.ToString();
// b dizinin 10 elamanına rasgele sayı uretme
Byte[] b=new byte[10];
Random rnd=new Random();
rnd.NextBytes(b); // 10 elemanlı b dizin rasgele sayı olur
39
Visual Studio 2010 .Net C#
label4.Text=b[1].ToString();
label5.Text=b[5].ToString();
}
•
Değer karşılaştırma ( Compare,Equals, Concat, Empty )
iki degeri kontrol etme
1. yöntem: compare( . , . ) ----> 0 cıkarsa aynı
2. yöntem: Equals( . , . ) ----> true , false
private void button9_Click(object sender, System.EventArgs e)
{
double x;
x=string.Compare("ataturk","at");
label4.Text=x.ToString(); // 1: var, -1:yok, 0:iki deger aynı
x=string.Compare("ataturk","mer");
label5.Text=x.ToString();
string bir,iki;
bir="turkiye"; iki="ankara";
if(string.Equals(bir,iki)==false)
{
MessageBox.Show("degerler farklı");
}
// string deger birleştirme (Concat)
string a1,a2;
a1="merve";
a2="volkan";
textBox3.Text=String.Concat(a1,"mehmet",a2,"bahriye");
// string degerin içerisini boşaltma(Empty)
textBox1.Text="";
textBox2.Text=string.Empty;
}
•
Dizin elemanları arasına karekter yerleştirme (join )
private void button10_Click(object sender, System.EventArgs e)
{
string[] isim=new string[3] {"faruk","merve","volkan"};
MessageBox.Show(string.Join(" * ",isim,0,3)); // faruk * volkan * merve
}
•
Uzunluk ( Lenght) , Pozisyon bulma (IndexOf )
private void button11_Click(object sender, System.EventArgs e)
{
// pozisyonu bulma
string isim="denizli"; // 7 karekter var . 0-6 pozisyon
40
Visual Studio 2010 .Net C#
int t;
// MessageBox.Show(isim.Length.ToString()); // 7
// t=isim.IndexOf("d",0,isim.Length); // 1. karekterden 7. karektere kadar bak
// label4.Text=t.ToString(); // 0.pozisyon
// t=isim.IndexOf("i",0,isim.Length);
// label4.Text=t.ToString(); // 3. pozisyon
t=isim.IndexOf("i",5,2); //5. karekterden basla. 5+2= 7 karektere kadar bak
label4.Text=t.ToString(); // 6. pozisyon
}
•
Karekter girişi ( Insert)
private void button11_Click_1(object sender, System.EventArgs e)
{
string deger1="ege üniversitesi";
label4.Text=deger1.Insert(5,"-bilgi-"); //ege ü-bilgi-niversitesi
}
•
Karekter Silme ( Remove )
private void button16_Click(object sender, System.EventArgs e)
{
string deger1="denizli";
label4.Text=deger1.Remove(3,2); //denli
}
•
Karekter Değiştirme ( Replace)
private void button13_Click(object sender, System.EventArgs e)
{
string deger1="denizli";
label4.Text=deger1.Replace("den","pam"); //pamizli
}
•
Karekter çıkarma ( Substring)
private void button14_Click(object sender, System.EventArgs e)
{
string deger1="denizli";
label4.Text=deger1.Substring(3,2); // istenilen karekter cıkarılır.
}
•
iz
Büyük Harfe çevirme ( ToUpper )
private void button15_Click(object sender, System.EventArgs e)
{
string deger1="denizli";
label4.Text=deger1.ToUpper(); //DENİZLİ
}
41
Visual Studio 2010 .Net C#
•
küçük Harfe çevirme ( ToUpper )
private void button17_Click(object sender, System.EventArgs e)
{
string deger1="PAMUKKALE";
label4.Text=deger1.ToLower(); //pamukkale
}
•
Boşluğu cıkarma ( Trim)
private void button18_Click(object sender, System.EventArgs e)
{
string deger1=" abc ";// 2 bosluk abc 2 bosluk = 7 karekter
label4.Text=deger1.Length.ToString(); // 7
// label5.Text=deger1.TrimStart().Length.ToString(); // 5 Bastaki 2 boşlugu atar
// label5.Text=deger1.TrimEnd().Length.ToString(); // 5 Sondaki 2 boşlugu atar
label5.Text=deger1.Trim().Length.ToString(); // 3 Bastakive sondaki 2 boşlugu atar
}
•
Tarih Fonsiyonları
private void button12_Click(object sender, System.EventArgs e)
{
//label4.Text=DateTime.MaxValue.ToString();//max tarih 31.12.9999 23:59:59
//label5.Text=DateTime.MinValue.ToString();// min tarih 01.01.001 00:00:00
//label6.Text=DateTime.Now.ToString(); // aktif tarih ve saat
//label7.Text=DateTime.Today.ToString(); // aktif tarih
//label4.Text=DateTime.Today.Day.ToString();
//gun'u verir
//label5.Text=Convert.ToDateTime("05/02/2002").Day.ToString(); //gun'u verir 5
//label5.Text=Convert.ToDateTime("05-02-2002").Day.ToString(); // tarih - ile kullanıldı
//label5.Text=Convert.ToDateTime(textBox1.Text).Day.ToString(); // textbox'tan deger alma
//label4.Text=DateTime.Today.Month.ToString();
//ayı verir 10
//label5.Text=DateTime.Today.Year.ToString();
//yılı verir
// label4.Text=DateTime.Today.DayOfYear.ToString();
//2bu gune kadar 275 gun vardır
// label5.Text=DateTime.Today.DayOfWeek.ToString();
// sunday
// label6.Text=DateTime.Today.AddYears(2).ToString();
//2 yıl sonraki tarih.yıl ekleme
// label7.Text=DateTime.Today.AddMonths(1).ToString(); //1 ay sonraki tarih .ay ekleme
// label7.Text=DateTime.Today.AddDays(6).ToString();
//6 gun sonraki tarih.gun ekleme
}
•
Directory Yaratma ( Create Directory )
private void button19_Click(object sender, System.EventArgs e)
{
// using System.IO; olarak ekleme yaparız
// directory yaratma
/*
Directory.CreateDirectory("D:\\muh");
Directory.CreateDirectory("D:\\muh\\sabit");
Directory.CreateDirectory("D:\\muh\\bil");
// directory silme
Directory.Delete("d:\\muh\\bil");
42
Visual Studio 2010 .Net C#
if(Directory.Exists("D:\\muh\\sabit")==false)
{
Directory.CreateDirectory("D:\\muh\\sabit");
}
if(Directory.Exists("D:\\muh\\bil"))
{
Directory.Delete("D:\\muh\\bil");
}
*/
// directory listeleme
string[] far=Directory.GetDirectories("d:\\");
foreach(string tek in far )
listBox1.Items.Add(tek);
}
•
Program Listeleme ( directory.GetFiles )
private void button20_Click(object sender, System.EventArgs e)
{
// program listeleme
string[] far=Directory.GetFiles("d:\\net");
foreach(string tek in far )
listBox1.Items.Add(tek);
}
•
Sürücü Listeleme (Directory.GetLogicalDrives )
private void button21_Click(object sender, System.EventArgs e)
{
// sürücü listeleme
string[] far=Directory.GetLogicalDrives();
foreach(string tek in far )
listBox1.Items.Add(tek);
}
•
Dosya Kopyalama
private void button22_Click(object sender, System.EventArgs e)
{
// using System.IO ; ekleme yapmalıyız
// dosya kopyalama
FileInfo dosya=new FileInfo("d:\\muh\\dene.txt"); // dosyayı isaretleriz
dosya.CopyTo("d:\\muh\\gul.txt",true); // kopyalama
}
•
Dosya Taşıma
private void button23_Click(object sender, System.EventArgs e)
{
// dosya tasıma
FileInfo dosya=new FileInfo("d:\\muh\\dene.txt"); // dosyayı isaretleriz
dosya.MoveTo("d:\\muh\\can.txt"); // tasıma
}
43
Visual Studio 2010 .Net C#
•
Dosya Silme
private void button24_Click(object sender, System.EventArgs e)
{
FileInfo dosya=new FileInfo("d:\\muh\\can.txt"); // dosyayı isaretleriz
if(dosya.Exists)
{
dosya.Delete();
MessageBox.Show("dosya silindi");
}
else
{
MessageBox.Show("dosya bulunmadı");
}
}
•
Dosyanın directory,Uzunluk ve ismi
private void button25_Click(object sender, System.EventArgs e)
{
FileInfo dosya=new FileInfo("d:\\muh\\gul.txt");
label4.Text=dosya.Directory.ToString(); //dosyanın bulundugu directory
label5.Text=dosya.Length.ToString(); // dosyanın uzunlugu
label6.Text=dosya.Name; // dosyanın ismi
}
•
Yeni Bir Dosya oluşturma
private void button26_Click(object sender, System.EventArgs e)
{
StreamReader oku=new StreamReader("d:\\muh\\gul.txt");
StreamWriter yaz=new StreamWriter("d:\\muh\\bilanco.txt");
//StreamWriter yaz=new StreamWriter("\\\\server1\\kredi\\bilanco.txt"); network erişim
string satir;
while (( satir=oku.ReadLine())!=null)
{
yaz.WriteLine(satir);
}
oku.Close();
yaz.Close();
}
•
Bir TextBox alanı text dosyaya kayıt etme
private void button27_Click(object sender, System.EventArgs e)
{
// dosya olustur
// textbox'ta birden fazla satır girmek için properties'de multiline=true yaparız
StreamWriter yaz=new StreamWriter("d:\\muh\\person.txt");
yaz.WriteLine(textBox1.Text);
yaz.Close();
}
44
Visual Studio 2010 .Net C#
•
Bir Text Dosyayı Listitem’a taşıma
private void button28_Click(object sender, System.EventArgs e)
{
StreamReader oku=new StreamReader("d:\\muh\\gul.txt");
string satir;
while (( satir=oku.ReadLine())!=null)
{
listBox1.Items.Add(satir);
}
oku.Close();
}
•
Textbox veya label’a Text dosyadan okuma
private void button29_Click(object sender, System.EventArgs e)
{
// farklı yöntemle tekbox veya label'a dosya okuma
StreamReader oku=File.OpenText("d:\\muh\\gul.txt");
textBox1.Text=oku.ReadToEnd();
oku.Close();
}
45
Visual Studio 2010 .Net C#
Events’lar
Mouse sol ,sağ, orta buton tıkalyınca mesaj yazması. Mouse down veya Mouse up ‘da aynı
sonucu alırız.
if(e.Button==MouseButtons.Left)
{
MessageBox.Show("sol tusa bastınız ..");
}
else if(e.Button==MouseButtons.Right)
{
MessageBox.Show("sag tusa bastınız ");
}
else if(e.Button==MouseButtons.Middle)
{
MessageBox.Show("sag tusa bastınız ");
}
label1.Text=" x koordinatı:"+e.X+"
y koordinatı ..:"+e.Y;
Event Oyun ( Butona tıklayamama )
Mouse tıklamak için hareket edince butonda hareket eder.
private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
46
Visual Studio 2010 .Net C#
{
button1.Left=e.X+30;
button1.Top=e.X+30;
}
Event
click
TextChanged
MouseDown
MouseUp
MouseMove
MouseEnter
MouseHover
Closing
Closed
Açıklama
Mouse Sol botuna tıklama
Textbox içeriğinin değişmesi
Mouse’da herhagi butona tıklama
MouseDown ile aynıdır
MouseDown ve MousUp gibidir. Yalnız tıklama ile degil, hareket iledir.
Mouse üzerine gelince bir kez işler
Mouse hareketsiz kalırsa otomatik işler.
Form kapatılırken . e.Cancel=true ile kapanması engellenir.
Farm Kapatılırken. E.Cancel kullanılamaz.Değişiklik kaydedilsinmi
uyarı kullanılır.
Load
Form çalıştırıldığında devreye girer.
Enter
Textbox değişkene gelince ( tab ile ) çalışır
Leave
Textbox değişkeni geçince çalışır.
Validating
Textbox değişkene gelince calışır
AutoSizeChanged
Size değişince
EnabledChanged
Kontrolün Enabled özelliği değişince
fontChanged
Font değişince
ForeColorChanged Yazı iç rengi değişmesince
BackColorChanged Yazı diş rengin değişmesiyle
MultiLineChanged
Textbox’da multiline true veya false olunca
ReadOnlyChanged Read özelliği değişince
KeyDown
Klavyeden herhangi bir tuşa basılmasıyla
Klavyedeki Tuşların kontrolu
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode==Keys.A)
{
MessageBox.Show("A tuşuna basıldı");
}
else if(e.KeyCode==Keys.B)
{
MessageBox.Show("B tuşuna basılıd");
}
47
Visual Studio 2010 .Net C#
else if(e.KeyCode==Keys.B)
{
MessageBox.Show("B tuşuna basıldı");
}
else if(e.KeyCode==Keys.Left)
{
MessageBox.Show("Sol ok tuşuna basıldı");
}
else if(e.KeyCode==Keys.F3)
{
MessageBox.Show("F3 tuşuna basıldı");
}
else if(e.KeyCode==Keys.Escape)
{
MessageBox.Show("escape tuşuna basıldı");
}
else if(e.KeyCode==Keys.PageUp)
{
MessageBox.Show("Page up tuşuna basıldı");
}
else
MessageBox.Show("Herhangi bir tuşa bastınız");
label1.Text=e.KeyValue.ToString(); // ascii kodu yazar
}
Alt ,Control, Shift ile birlikte basılan kontrol
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.Alt==true)
{
if(e.KeyCode==Keys.Return)
{
MessageBox.Show("alt-enter'a basıldı..");
}
}
if(e.Control==true)
{
if(e.KeyCode==Keys.Return)
{
MessageBox.Show("Control-enter'a basıldı..");
}
}
if(e.Shift==true)
{
if(e.KeyCode==Keys.D)
{
MessageBox.Show("shift-D'e basıldı..");
}
}
}
48
Visual Studio 2010 .Net C#
Formu kapatma
Kapatmada soru sordurma. Kapatmayı durdurabiliriz( e.cancel=true ; )
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
DialogResult mesaj;
mesaj=MessageBox.Show("kapatmak istiyormusunuz", "kapat",MessageBoxButtons.YesNo);
if ( mesaj==DialogResult.No)
{
e.Cancel=true; // Kapatmayı durdurma
}
else
{
MessageBox.Show("program kapatılıyor..");
}
}
Kesin Kapatma. Yalnız son bir işlem ( kayıt gibi ) yapma
private void Form1_Closed(object sender, System.EventArgs e)
{
DialogResult mesaj;
mesaj=MessageBox.Show("degişiklikler kaydedilsinmi","kapat",MessageBoxButtons.YesNo);
if ( mesaj==DialogResult.Yes)
{
// kayıt kodları yazılır
MessageBox.Show(" değişiklikler kaydedildi ...");
}
}
Form Yüklemede şifre kullanma
private void Form1_Load(object sender, System.EventArgs e)
{
// project-add referance ile Mic. visual basic runtime eklenir.
int sayi=1;
string sifre;
sifre= Microsoft.VisualBasic.Interaction.InputBox("sifreyi giriniz" , "sifre
girisi","",100,200);
while(sifre!="faruk")
{
if(sayi>3)
{
break;
}
else
{
sifre= Microsoft.VisualBasic.Interaction.InputBox("sifreyi giriniz","sifre
girisi","sifre tekrar",100,200);
sayi++;
}
}
if(sayi>=3)
{
MessageBox.Show("3 hakkınızıda bilemediniz.Yeniden deneyiniz");
Application.Exit();
}}
49
Visual Studio 2010 .Net C#
Bazı tuşların textbox’a girişini Engelleme
private void textBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
// 48-57 sayılar . A=65,B=66,C=67,D=68. Backspace=10
// A,B,C,D harflerinin textbox'a girilmesini engellemek için; if ((e.KeyChar >=
(char)65) && (e.KeyChar <= (char)68))
if ((e.KeyChar > (char)10) && (e.KeyChar < (char)48) || (e.KeyChar > (char)57))
{
e.Handled = true;
}
label1.Text = e.KeyChar.ToString(); // bütün tusları label'a yazdırma
}
Form Başlığı
button gibi yerde değişiklik:
Form1.ActiveForm.Text=”personel sistemi”;
veya
This.Text=”personel sistemi
Load event’ta ( yükleme sırasında ) :
This.Text=”personel sistemi”;
50
Visual Studio 2010 .Net C#
Esc ve Enter Tuşlarını button’lara tanımlama
Biz form load avent’ta veya form active event’ta Enter veya esc basınca buton tıklanmış gibi
çalışacak hale getiririz.
Active ‘de tanım yaparsak Form1.ActiveForm , load’da tanım yaparsak this
kullanırız.
•
Form Load’ta tanımlama
private void Form1_Load(object sender, System.EventArgs e)
{
this.Text="muhasebe sistemi";
this.AcceptButton=button1; // enter tuşuna basınca button1 calışır
this.CancelButton=button2; // esc tuşuna basınca button2 çalışır
}
•
Form Active’de tanım
private void Form1_Activated(object sender, System.EventArgs e)
{
Form1.ActiveForm.AcceptButton=button1;
Form1.ActiveForm.CancelButton=button2;
}
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("enter basıldı..");
}
private void button2_Click(object sender, System.EventArgs e)
{
MessageBox.Show("ESC basıldı..");
}
51
Visual Studio 2010 .Net C#
Form özelliklerini değiştirme
Forms’a ait özellikleri properties penceresinden manual veya action’dan form1_load’a
kodlama ile yapılır.
52
Visual Studio 2010 .Net C#
Buton ekleme
Forms üzerinden veya kodlama ile yaparız.
Button yeni = new Button();
this.Controls.Add(yeni);
yeni.Left = 50;
yeni.Top = 100;
yeni.Text = "arama";
53
Visual Studio 2010 .Net C#
Menu Oluşturma
1.Yöntem : Buton ile
Form Çagırma
•
•
C# girince form1 gelir.
3 adet ek form oluşturulur. ( Project --- add windows form )
54
Visual Studio 2010 .Net C#
Form1 ana formundan form2,form3,form4’ü buton ile çağırıyoruz.
Form Çağırma
Form2 pen=new Form2();
pen.Show();
Form2 gelir.form2 ve form1’de
çalışabiliriz.
Form2 pen=new Form2();
pen.ShowDialog();
Form2 gelir.sadece form2’de
çalışabiliriz.Aktif olan form2 ‘ye izin
verir.
Uygulamadan Çıkış
Form’u kapatma
Application.Exit();
this.Close();
aktif formu kapat .
Formu gizleme
Form2.ActiveForm.Close();
this.hide();
Form4.ActiveForm.Hide();
form2'yi kapat
Aktif form'u gizler.
Form4’ü gizler.
Anamenu Formu
private void button1_Click(object sender, System.EventArgs e)
{
Form2 pen=new Form2();
pen.Show();
}
private void button2_Click(object sender, System.EventArgs e)
{
Form3 pen=new Form3();
pen.ShowDialog();
}
private void button4_Click(object sender, System.EventArgs e)
{
Form4 rapor=new Form4();
rapor.Show();
}
private void button3_Click(object sender, System.EventArgs e)
{
Application.Exit();
}
Personel Formu
private void button1_Click(object sender, System.EventArgs e)
{
this.Close(); // aktif formu kapat .Altaki ile aynıdır
// Form2.ActiveForm.Close(); // form2'yi kapat
}
55
Visual Studio 2010 .Net C#
Maas Formu
private void button1_Click(object sender, System.EventArgs e)
{
this.Close();
}
Forms4 formu
private void button1_Click(object sender, System.EventArgs e)
{
//this.Hide(); // form4'ü gizler. Daha cok ths.close() kullanırız.
Form4.ActiveForm.Hide(); //
"
"
"
}
2.Yöntem : MenuStrip ile
•
•
•
•
toolbox’dan Mainmenu cift tıklanır
Form1’in altına gelen mainmenu’ye bir kez tıklarız. Formun üstünde
Type Here cıkar. Type Here üzerine tanımlar yazarız. Altına sigorta
gibi şeklinde menu isimlerini gireriz.
Sigortaya, personel’e, Cıkış2a cift tıklayıp kodlamayı yaparız.
Kodlama
Midi-child form için form özelliklerinde IsMdiContainer=true
yaparız. Form cagırırken mMdiParent=this özelliğini kullanırız.
private void cıkısToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void sskToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 ssk=new Form2();
ssk.MdiParent=this; // child form ( yavru) için
ssk.Show();
}
56
Visual Studio 2010 .Net C#
private void faturaToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(" Sayfa yapım asamasındadır ...");
}
57
Visual Studio 2010 .Net C#
3.Yöntem : ToolStrip ile
Resim butonlu menu hazırlamadır. toolStrip sürüklenerek veya çift tıklanarak form1’in
üstünde cubuk şeklinde yer alır. Form1 sayfasının daha iyi menülü görüntüsünü saglamak
için ; lsmdicontainer’’i true yaparız.
•
Butonların Özelliklerinde(properties)
58
Visual Studio 2010 .Net C#
o
o
o
Text : toolbar’daki butonun görünen adı . personel,stok,cıkıs
Tooltip : runtime’da Mouse butonun üzerine gidince help bilgisi
Image : Buton resmi
Resimli butonlara tıklayarak kodlama yaparız.
private void toolStripButton1_Click(object sender, EventArgs e)
{
Form2 yeni = new Form2();
// yeni.MdiParent = this; // Form2 , form1 içersinde baglı gelir.
yeni.Show();
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
MessageBox.Show("sayfa yapım asamasındadır ..");
}
private void toolStripButton4_Click(object sender, EventArgs e)
{
Application.Exit();
}
59
Visual Studio 2010 .Net C#
Web Sayfasına Bağlantı
•
•
•
•
Toolbox’dan linklabel tıklanır.
Text’ten ismi değiştirilir. ( milliyet gazatesi )
Linklabel’ın font’u, Linkcolor’ı properties’lerden değiştirilir.
Form load event’ta milliyet gazatesi yazısının kac karekteri tıklamayı kabuletsin
yapılır. Yani Mouse ile üzerine gelince tıklamaya müsait olsun yapılır.
Private void Form1_Load(object sender, System.EventArgs e)
{
linkLabel1.Links.Add(0,8,”http://www.milliyet.com.tr”);
}
•
Web adresine gitme linlabel etiketine cift tıklayarak yazılır.
private void linkLabel1_LinkClicked(object sender,
System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
}
•
Runtime’da Milliyet gazatesine cift tıklayınca www.milliyet.com.tr’a gider. Yani
Internet Explorer çalışır.
60
Visual Studio 2010 .Net C#
Cursor Textbox’da iken F1 basınca Yardım ( helpProvider )
private void Form1_Load(object sender, System.EventArgs e)
{
helpProvider1.SetHelpString(textBox1,"kodu girilecek");
helpProvider1.SetHelpString(textBox2,"tekstil birim fiyatı girilecek");
helpProvider1.SetHelpString(textBox3,"adet girilecek");
}
Form1_load : Form yüklenirken calışır.
61
Visual Studio 2010 .Net C#
Hata kontrol Mesajı ( errorprovider )
•
Değişkenlere istenilen deger girilmedi zaman kırmızı yuvarlak olarak işaretle
gösterir. Yuvarlak daire üzerine Mouse ile gelince mesaj verir.
private void button1_Click(object sender, System.EventArgs e)
{
if(textBox1.Text=="")
{
errorProvider1.SetError(textBox1,"kodu giriniz");
}
else
{
errorProvider1.SetError(textBox1,"");}
if(textBox2.Text=="")
{
errorProvider1.SetError(textBox2,"fiyatı giriniz");
}
else
{errorProvider1.SetError(textBox2,"");}
if(textBox3.Text=="")
{
errorProvider1.SetError(textBox3,"adeti giriniz");
}
else
{ errorProvider1.SetError(textBox3,""); }
}
62
Visual Studio 2010 .Net C#
Büyük, Küçük ve şifreli Giriş
Örnek TextBox kodlamaları :
textrBox1.Width=textBox1.Width+50;
textBox1.Font= new Font (“Arial”,20);
textBox2.Focus(); // textBox2 git
TextBox textBox1=new TextBox();
textBox1.Location=new Point(0,0);
textBox1.Size=new Size(152,20);
63
Visual Studio 2010 .Net C#
Button Özellikleri
•
•
•
TextBox veya Buton üzerine Mouse ile gelince acıklama yazması
ALT ile bir karekter (A,B gibi ) tıklayıca buton çalışır
Butonun görüntü değişikliği
private void Form1_Load(object sender, System.EventArgs e)
{
ToolTip goster=new ToolTip();
goster.SetToolTip(this.button1,"personel hesaplama yapar");// button
üzerine gelince yazar
goster.SetToolTip(this.textBox1,"urunun fiyatı"); // textbox'ın
üzerine gelince yazar
button1.Text="&Rapor"; // alt tusuyla R 'de çalışır
}
64
Visual Studio 2010 .Net C#
Checkbox, Radiobutton, Listbox,combobox Kontrolu
•
checkBox
private void button1_Click(object sender, System.EventArgs e)
{
checkBox2.Checked=true;
checkBox2.FlatStyle=FlatStyle.Flat;
checkBox3.FlatStyle=FlatStyle.Popup;
if (checkBox1.Checked==true)
{
MessageBox.Show("Đngilizce biliniyor..");
}
else
{MessageBox.Show("Đngilizce bilinmiyor..");}
}
•
}
RadioButton
1. Groupbox cift tıklanır
2. groupbox seçiliyken radiobutton cift tıklanır
private void button2_Click(object sender, System.EventArgs e)
{
radioButton1.Checked=true;
if (radioButton5.Checked==false)
{ MessageBox.Show("fransızca bilmiyor..");}
}
65
Visual Studio 2010 .Net C#
•
ListBox
private void button3_Click(object sender, System.EventArgs e)
{
listBox1.Items.Add("mehmet"); // ekleme
// if (textBox1.Text!="") {listBox1.Items.Add(textBox1.Text);}
textBox1.Text=listBox1.Text; // Secili olanı texbox'a at
listBox1.Items.Remove("Merve");// Silme
listBox1.SetSelected(0,true); // ilk kayıtı sec
MessageBox.Show(listBox1.Items.Count.ToString()); // toplam
}
•
Combobox
private void button4_Click(object sender, System.EventArgs e)
{MessageBox.Show(comboBox1.Text);// secili elemanı yazar
MessageBox.Show(comboBox1.SelectedIndex.ToString()); // secili
elamanın index nosunu verir 0'dan başlar
}
66
Visual Studio 2010 .Net C#
Tabmenu hazırlama
•
Toolbox’dan tabcontrol cift tıklanarak form1’e tabmenu getirilir.
•
Tabemenu üzerinde sağ Mouse- add tab ile tab sayfa’lar eklenir.( tabpage2 gibi)
•
Tabpage’lerin ismi değiştiririz. Tabmenudeki tabpage2 tıklarız - altındaki diktörtgene
tıklarız -- properties’den Text ‘in degerini ( tabpage2) değiştiririz.
•
Tabmenu’nin içindeki önce tabpage1( musteri) sonra diktörtgen alan tıklanır.ve içerine
textbox veya label getiririz.(toolbox’tan cift tıklayarak ). Aynı işkelemi tabpage2(ssk)
içinde yaparız.
67
Visual Studio 2010 .Net C#
private void button1_Click(object sender, System.EventArgs e)
{
tabControl1.SelectedTab=tabPage2; // ssk ‘a gecer
}
Agaç görünümlü Kontrol ( treeView )
68
Visual Studio 2010 .Net C#
private void button2_Click(object sender, System.EventArgs e)
{
label3.Text=treeView1.SelectedNode.Text; // secili olan satırı gosterir
//label3.Text=treeView1.SelectedNode.Index.ToString(); //secili elemanın
kacıncı pozisyon oldugu yazar
//label3.Text=treeView1.Nodes.Count.ToString();//ana kayıtların toplam
sayısı
// ********** EKLEME ***************************
//treeView1.Nodes.Add("ankara");//en sona ana ekleme yapar
//treeView1.SelectedNode.Nodes.Add("bogazkoy");//secili olana ekler
//treeView1.Nodes[0].Nodes.Add("bornova"); //ilk kayıta baglı alt ekleme
//treeView1.Nodes[0].Nodes[0].Nodes.Add("belkahve"); //ilk kayıta baglı alt
kayıtın altına ekler
//treeView1.Nodes[3].Nodes.Add("bakırkoy"); //4. kayıta baglı alt ekleme
// *********** SILME **************************
//treeView1.Nodes.Remove(treeView1.SelectedNode);//secimli olanı siler
//treeView1.Nodes.Remove(treeView1.Nodes[1]);// 1.pozisyonu siler
//treeView1.Nodes.Clear();// hepsini siler
//treeView1.CheckBoxes=true;//secimli kare eklenir
//treeView1.ExpandAll(); //alt kayıtları acar
//treeView1.CollapseAll();// alt kayıtları toplar
//treeView1.ShowLines=true;//kenarındaki cizgileri gosterir veya kaldırır
//label3.Text=treeView1.SelectedNode.Checked.ToString();// sectigim kayıtte
checkbox işaretlimi.true,false
}
imageList ve listView
•
•
imageList ve listView toolbox’tan eklenir.
İmagelist’e resimler eklenir( imagelist1-properties(images) -- add)
69
Visual Studio 2010 .Net C#
private void button3_Click(object sender, System.EventArgs e)
{
listView1.Items.Add("person");
listView1.Items.Add("muh-d",0);//imagelist'deki 0 pozisyondaki resmide ekle
//listView1.Clear();// hepsini siler
//listView1.Items.RemoveAt(1);//1. pozisyonu, yani 2.kayıtı siler
//label5.Text=listView1.Items.Count.ToString(); // kayıt sayısını verir
}
Tarih Secme(DateTimePicker )
-- Cıkan tarih menusunden tarih seceriz.
70
Visual Studio 2010 .Net C#
private void button1_Click(object sender, System.EventArgs e)
{
label1.Text=dateTimePicker1.Text;// secilen tarihi alır
}
Scrollbar kontrolu
dikey ve yatay scroll saga,sola veya ust,alta gidince resmin boyutu
değişir.
private void vScrollBar1_Scroll(object sender,
System.Windows.Forms.ScrollEventArgs e)
{
pictureBox1.Height=vScrollBar1.Value+1;
}
private void hScrollBar1_Scroll(object sender,
System.Windows.Forms.ScrollEventArgs e)
{
pictureBox1.Width=hScrollBar1.Value+1;
}
71
Visual Studio 2010 .Net C#
Timer ( Zaman Kontrolu )
public static string mesaj="pamukkale Üniversitesi
2.Sınıf";
public static int x=1;
Egitim Fakultesi Bote
private void Form1_Load(object sender, System.EventArgs e)
{
timer1.Interval=500; //1 sn bekle
timer1.Enabled=true; // timer baslar
//timer1.Start();
// timer baslar
// timer1.Stop(); // timer durur
//timer1.Enabled=false; // timer durur
}
private void timer1_Tick(object sender, System.EventArgs e)
{
label1.Text=mesaj.Substring(x,mesaj.Length-x);
if(x==mesaj.Length-1){x=0;}
x++;
}
72
Visual Studio 2010 .Net C#
statusStrip ( Formun altında mesaj verir, Kullanıcıyı bilgilendirme )
Formun alt tarafında durum cubugu oluşturarak kullanıcıyı bilgilemdirme yapabiliriz.
toolStripStatusLabel1.Text = "kodu ve adı giriniz";
gibi.
private void button1_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "kodu ve adı giriniz";
}
73
Visual Studio 2010 .Net C#
Dosya okuma ve yazma( openFileDialog,saveFileDialog )
using System.IO;
//ekleme
yapılmalıdır.
Sadece dosya isimlerini getirme :
private void button3_Click(object sender, EventArgs e)
{
//openFileDialog1.ShowDialog();// acma penceresi.tek kullanılabilir.
openFileDialog1.Title = "personel resim dosyası";//gelecek pencerenin baslıgı
openFileDialog1.DefaultExt = "exe";//varsayılan extention exe kullan
openFileDialog1.Filter = "jpg files |*.jpg|butun file|*.*"; // iki filter
openFileDialog1.FilterIndex = 1; // 1.filterı kullan(*.jpg"
openFileDialog1.InitialDirectory = "d:\\temp";
openFileDialog1.Multiselect = true;// shiftle birden fazla dosya ac
openFileDialog1.ShowDialog();// acma penceresi gelir
//label1.Text=openFileDialog1.FileName; // bir dosya için
foreach (string muh in openFileDialog1.FileNames) // birden fazla dosya için
{
//label1.Text = label1.Text + " - " + muh;
// label1'e
getirme
textBox1.Text = textBox1.Text + " - " + muh; // textbox1'e getirme
}
dosya okuma : text bir dosyadan okuma
private void button1_Click(object sender, EventArgs e)
{
string satir;
openFileDialog1.Title = "dosya okuma";
openFileDialog1.ShowDialog();
StreamReader oku = new StreamReader(openFileDialog1.FileName);
while ((satir = oku.ReadLine()) != null)
{
textBox1.Text += satir + (char)13 + (char)10;
}
oku.Close();
}
74
Visual Studio 2010 .Net C#
dosya yazma: Hazır bir text dosyasına kayıt eder
private void button2_Click(object sender, EventArgs e)
{
string satir;
openFileDialog1.Title = "dosya yazma";
openFileDialog1.ShowDialog();
StreamWriter yaz = new StreamWriter(openFileDialog1.FileName);
yaz.WriteLine(textBox1.Text);
yaz.Close();
}
TrackBar
Bir resmin büyütülüp , küçültülmesi
private void trackBar1_Scroll(object sender, System.EventArgs e)
{
pictureBox1.Width=trackBar1.Value*10;
pictureBox1.Height=trackBar1.Value*10;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
//MessageBox.Show(trackBar1.Value.ToString());// trackbar 0-10
arasındaki degeri
pictureBox1.Width = trackBar1.Value * 20;
pictureBox1.Height = trackBar1.Value * 20;
}
75
Visual Studio 2010 .Net C#
progressBar
•
•
•
Toolbox’dan progressbar’ı cift tıklayarak getiririz. Prograssbar’ın properties degeri 0 100 arasın value’dir. Biz istersek properties’den bu degerleri degiştirebiliriz.
Progressbar’da deger artışını göstermek için timer’dan yararlandık.baslat buton’da
timer’ı baslattık. Dur butonda durdurduk.Aynı zamanda label1’dede progressbar’ın
value degerini yazdırdık.
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value <= 95)
{
progressBar1.Value = progressBar1.Value + 5;
}
else
{
progressBar1.Value = 0;
}
label1.Text = "% " + progressBar1.Value.ToString() + " tamamlandı..";
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Interval = 400; // 1000: 1 saniye
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
76
Visual Studio 2010 .Net C#
toolTip
Objeleri ( resim,textbox,label …) üzerine geldiğimizde açıklama vermesidir. Formun
yüklenmesi event’ta ( Form1_Load) her obje ( textbox,label,buton…) için tanım yaparız.
private void Form1_Load(object sender, System.EventArgs e)
{
toolTip1.SetToolTip(label1,"progressbar'ın yüzdeliklerini gösterir");
toolTip1.SetToolTip(button1,"progress'i baslatır..");
toolTip1.SetToolTip(button2,"progress'i durdurur..");
}
Drag& Drop Yöntemi
•
•
Toolbox’dan iki adet listbox ‘ı forma getiririz.
Listbox1’e 3 adet üniversite kayıtı girilir. Lisbox1- properties - Items
77
Visual Studio 2010 .Net C#
listbox2’ye gelen sürüklenmiş nesneyi kabul et:
private void Form1_Load(object sender, System.EventArgs e)
{
listBox2.AllowDrop=true;
}
listbox’de Mouse ile tutularak sürüklenmek istenek kayıtı al :
private void listBox1_MouseDown(object sender,
System.Windows.Forms.MouseEventArgs e)
{
Point nokta=new Point(e.X,e.Y);
int index=listBox1.IndexFromPoint(nokta);
if(e.Button==MouseButtons.Left)
{
listBox1.DoDragDrop(listBox1.Items[index].ToString(),DragDropEffects.All);
}
}
gelen kayıtı listbox2’de kopya edecegim :
private void listBox2_DragOver(object sender,
System.Windows.Forms.DragEventArgs e)
{
if(e.KeyState==1) // hicbir tuş basılı degilse
{
e.Effect=DragDropEffects.Copy; // copy, All, lint,mode,scroll
}
}
listebox2’ye kayıtı ekle , listbox1’den sil:
private void listBox2_DragDrop(object sender,
System.Windows.Forms.DragEventArgs e)
{
listBox2.Items.Add(e.Data.GetData(DataFormats.Text).ToString());
listBox1.Items.Remove(e.Data.GetData(DataFormats.Text).ToString());
}
78
Visual Studio 2010 .Net C#
Registry File okuma,Yazma
Okuma:
using Microsoft.Win32; // Ekle
private void button1_Click(object sender, System.EventArgs e)
{
label1.Text=Registry.CurrentUser.OpenSubKey("Control Panel").OpenSubKey("Colors").GetValue("Menu").ToString();
}
Kayıt :
private void button2_Click(object sender, System.EventArgs e)
{
Registry.CurrentUser.CreateSubKey("pamukkale").CreateSubKey("kullanıcılar").SetValue("volkan",1240);
}
Değiştirme:
private void button3_Click(object sender, System.EventArgs e)
{
//directory'ler oldugu için sadece volkanın degeri 5000 olarak degiştirilir.
Registry.CurrentUser.CreateSubKey("pamukkale").CreateSubKey("kullanıcılar").SetValue("volkan",5000);
}
79
Visual Studio 2010 .Net C#
Silme:
private void button4_Click(object sender, System.EventArgs e)
{
// degeri silme
Registry.CurrentUser.CreateSubKey("pamukkale").CreateSubKey("kullanıcılar").DeleteValue("volkan");
// directory ve altını silme
Registry.CurrentUser.CreateSubKey("pamukkale").DeleteSubKeyTree("kullanıcılar");
Registry.CurrentUser.DeleteSubKeyTree("pamukkale");
}
80
Visual Studio 2010 .Net C#
User,Şifre ile Form Giriş
Hatırlatma:
Önceden kayıt ettiğimizi düşünelim. kullanıcı: volkan, sifre:1240 düşünelim.
Registry.CurrentUser.CreateSubKey("pamukkale").CreateSubKey("kullanıcılar").SetValue("volkan",1240);
Sifre=Registry.CurrentUser.OpenSubKey("pamukkale").OpenSubKey("kullanıcılar").GetValue(textBox
1.Text).ToString(); ---- textbox1’e volkan girersek sifre 1240 olarak okunur.
private static string sifre;
private void button5_Click(object sender, System.EventArgs e)
{
try
{
sifre=Registry.CurrentUser.OpenSubKey("pamukkale").OpenSubKey("kullanıcılar").GetValue(textBox1.Text).ToString();
}
catch
{
textBox1.ResetText();
textBox2.ResetText();
textBox1.Focus();
}
if(sifre==textBox2.Text)
{
Form2 yeni=new Form2();
yeni.Show();
}
else
{
textBox1.ResetText();
textBox2.ResetText();
textBox1.Focus();
label1.Text="sifre yanlıs..";
}
}
81
Visual Studio 2010 .Net C#
User Kontrolu
“ Bazı ekran formlarını belirli kurallarda şablon olarak hazırlayıp diğer formlarda kullanmayı
sağlar.”
•
•
Kontrol Hazırlama
Kontrol kullanma
Hazırlama :
Bir textbox ( sadece sayısal girişin oldugu not giriş alanı) hazırlayıp , bu şablonu her
form’da kullanalım.
•
Form1’e Bir label ve textbox getirelim.
82
Visual Studio 2010 .Net C#
•
Kodlamasını yapalım.
o
Public class ve public’in isimlerini değiştirelim. Çünkü Form’larda kullanırken
bu ismi sürükleyecegiz. Kontrol yapalım.
o
Bu textBox alana sadece sayılar girelim. Bu textbox’ı normal formalarda
kullandıgımız gibi ( icersine deger atma veya degerin alma gibi )
kullanamayız. Bu yüzden yedekdegiş isminde bir properties’de bulunan bir
degisken tanımlayıp bunu kullanıyoruz.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(e.KeyChar>=(char)58||(e.KeyChar<=(char)47)) // rakam dısında
{
if(e.KeyChar!=(char)8) // backspace tusu
{
e.Handled=true; // basılan tus iptal
}
}
}
public string yedekdegis
{
get
{
return textBox1.Text; // textbox'a girilen degeri yedekdegis'e al
}
set
{
textBox1.Text=value.ToString(); // yedekdegis'teki properties veya deger girişi textbox1'a al
}
}
83
Visual Studio 2010 .Net C#
•
Çalıştırıyoruz ve bir dll üretiyor.
Kullanma :
•
Toolbox penceresine bu hazırlamış oldugumuz kontrolu (userkontrol.dll) getiriyoruz.
( toolbox pencersinde -- sağ Mouse - add/remove items - .Net framework
components -- browse --- userkontrol.dll - ok ) . Ayrıca Toolbox’a gelen
kontrol dll’i sürükleyerek forma getiriyoruz.
84
Visual Studio 2010 .Net C#
•
Bir buton tanımlayıp , içersinde kodlama yapıyoruz. Kontrol1’in yedekdegis’i
messagebox ile ekranda yazdırıyoruz ve yedekdegis’e 250 degerini atıyoruz.
85
Visual Studio 2010 .Net C#
Microsoft Access ile kayıt işlemleri
1.Yöntem:
Visual c# projesi yaratılır.
Data Sources ( icon yoksa Data -- show data sources ile getiririz) --- add new data
source veya Data - add New data source ile Access dosyası ile baglantı kurulur.
86
Visual Studio 2010 .Net C#
87
Visual Studio 2010 .Net C#
Data source penceresinde oluşan adres Access table sürükleyerek sayfaya bırakılır. Grid
objesi,ileri,geri cubugu ve bağlantı iconları otomatik oluşur.
F5 ile bilgileri görebiliriz.
2.Yöntem:
Visual c# projesi yaratılır.
88
Visual Studio 2010 .Net C#
Button ve datagridview tık tık yaparak veya sürükleyerek sayfaya getirilir.
Datagrid1’in özelliklerinden datasource’a Access dosyasını getiririz.
89
Visual Studio 2010 .Net C#
Sayfa altında bağlantı iconları oluşur.
90
Visual Studio 2010 .Net C#
Datagridview1’in datasource’unu none yaparak button’a cift tıklar ve kodlamayı yaparız.
dataGridView1.DataSource = adresBindingSource;
F5 ile veya debug start debugging veya çalıştırma iconu ile
çalıştırdıgımız zaman button’a tıklarsak listeyi görebiliriz.
91
Visual Studio 2010 .Net C#
92
Visual Studio 2010 .Net C#
3.Yöntem:
Visual c# projesi yaratılır.
Button ve datagridview tık tık yaparak veya sürükleyerek sayfaya getirilir.
93
Visual Studio 2010 .Net C#
BindingSource iconu sürükleyerek veya tık tık yaparak sayfaya getirilir.
Bindingsource --- özelliklerden datasource’a Access dosyası girilir.
94
Visual Studio 2010 .Net C#
95
Visual Studio 2010 .Net C#
Data member’a adres table secilir. Bu arada persondataset adrestableadaptor iconları
sayfada oluşur.
Button’a cift tıklatarak kodlama yazılır.ve F5 ile çalıştırız ve butona tıklayınca sonucu
görürürüz.
dataGridView1.DataSource = bindingSource1;
96
Visual Studio 2010 .Net C#
97
Visual Studio 2010 .Net C#
Texbox’larda gösterme ve önceki, sonraki kayıtlara gecme
Visual c# projesi yaratılır.
Button ,Label ve Texbox tık tık yaparak veya sürükleyerek veya bir kez sayfaya
getirdikten sonra copy-paste ile getiririz.
98
Visual Studio 2010 .Net C#
Label, button objelerin özelliklerden ismini değiştiririz.
bindingSource1, sayfaya getirilir. Daha sonra özelliklerden DataSource değerine Access
dosyası , DataMember değerine Access table getirilir.
99
Visual Studio 2010 .Net C#
BindingSource1’in DataSource değerine Access dosyası girilir.
100
Visual Studio 2010 .Net C#
DataMember değerine adres table’ı girilir. Önceden getirdiğimiz BindingSource1
yanında PersonDataSet ve AdresTableAdaptor iconları otomatik oluşur.
101
Visual Studio 2010 .Net C#
Butonlara tek tek tıklanarak kodlama yapılır.
private void Form1_Load(object sender, EventArgs e)
{
// form ilk acılınca
this.adresTableAdapter.Fill(this.personDataSet.adres);
textBox1.DataBindings.Add("Text", personDataSet.adres,
textBox2.DataBindings.Add("Text", personDataSet.adres,
textBox3.DataBindings.Add("Text", personDataSet.adres,
textBox4.DataBindings.Add("Text", personDataSet.adres,
textBox5.DataBindings.Add("Text", personDataSet.adres,
}
"nosu");
"adi");
"soyadi");
"sehir");
"tel");
private void button1_Click(object sender, EventArgs e)
{
// ilk kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
sonra.Position = 0;
}
private void button2_Click(object sender, EventArgs e)
{
//Önceki kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
if (sonra.Position <= 0)
{
MessageBox.Show("baska kayıt kalmadı.ilk kayıttasınız");
}
else
{ sonra.Position -= 1; }
}
private void button3_Click(object sender, EventArgs e)
{
// Sonraki kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
if (sonra.Position >= sonra.Count - 1)
{
MessageBox.Show("baska kayıt kalmadı.Son kayıttasınız");
}
else
{ sonra.Position += 1; }
}
private void button4_Click(object sender, EventArgs e)
{
// En son kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
sonra.Position = sonra.Count - 1;
}
private void button5_Click(object sender, EventArgs e)
{
// Kayıt Silme
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
DialogResult son;
son = MessageBox.Show("kayıtı silmek istiyormusunuz...", "silme kontrolu",
MessageBoxButtons.YesNo);
if (son == DialogResult.Yes)
{
102
Visual Studio 2010 .Net C#
sonra.RemoveAt(sonra.Position);
adresTableAdapter.Update(personDataSet.adres);
}
else
{ MessageBox.Show("kayıt silinmedi..."); }
}
private void button6_Click(object sender, EventArgs e)
{
// database kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
sonra.EndCurrentEdit(); // dataset'e (ram) kayıt
adresTableAdapter.Update(personDataSet.adres);
// database'e kayıt
MessageBox.Show("Database kayıt yapıldı..");
}
private void button7_Click(object sender, EventArgs e)
{
// Arama
int t = 0, b = 0;
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
foreach (DataRow satir in personDataSet.adres.Rows)
{
if (satir[0].ToString() == textBox6.Text)
{
sonra.Position = t; b = 1;
return; //for'dan cık
}
t++;
}
if (b == 0) MessageBox.Show("kayıt bulunamadı...");
}
private void button8_Click(object sender, EventArgs e)
{
// Kayıt giriş başlama
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
sonra.AddNew();
textBox1.Focus();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// form cıkışta otomatik database'e kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
sonra.EndCurrentEdit(); // datase'e(ram) kayıt
adresTableAdapter.Update(personDataSet.adres); // database'e kayıt
}
private void button9_Click(object sender, EventArgs e)
{
Application.Exit();
}
103
Visual Studio 2010 .Net C#
Form’dan cıkarken otomatik bir kodlama çalışması için formun boş bir yeri tıklanır.
Özelliklerden Event( Triger) bölümde FormClosed cift tıklanarak aşagıdaki kodlama
yapılır.yani cıkışta otomatik kayıt yapsın.
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// form cıkışta otomatik database'e kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[personDataSet.adres];
sonra.EndCurrentEdit(); // datase'e(ram) kayıt
adresTableAdapter.Update(personDataSet.adres); // database'e kayıt
}
Fonksiyonlu Kullanım
private void Form1_Load(object sender, EventArgs e)
{
// form ilk acılınca
this.adresTableAdapter.Fill(this.personDataSet.adres);
textBox1.DataBindings.Add("Text", personDataSet.adres,
textBox2.DataBindings.Add("Text", personDataSet.adres,
textBox3.DataBindings.Add("Text", personDataSet.adres,
textBox4.DataBindings.Add("Text", personDataSet.adres,
textBox5.DataBindings.Add("Text", personDataSet.adres,
"nosu");
"adi");
"soyadi");
"sehir");
"tel");
}
private CurrencyManager sonra;
private void arac(personDataSet aa)
//private void arac(DataSet aa)
{
//sonra = (CurrencyManager)this.BindingContext[aa.Tables[0]];
sonra = (CurrencyManager)BindingContext[aa.adres];
}
private void button1_Click(object sender, EventArgs e)
{
// ilk kayıt
arac(personDataSet);
sonra.Position = 0;
}
104
Visual Studio 2010 .Net C#
private void button2_Click(object sender, EventArgs e)
{
//Önceki kayıt
arac(personDataSet);
if (sonra.Position <= 0)
{
MessageBox.Show("baska kayıt kalmadı.ilk kayıttasınız");
}
else
{ sonra.Position -= 1; }
}
private void button3_Click(object sender, EventArgs e)
{
// Sonraki kayıt
arac(personDataSet);
if (sonra.Position >= sonra.Count - 1)
{
MessageBox.Show("baska kayıt kalmadı.Son kayıttasınız");
}
else
{ sonra.Position += 1; }
}
private void button4_Click(object sender, EventArgs e)
{
// En son kayıt
arac(personDataSet);
sonra.Position = sonra.Count - 1;
}
private void button5_Click(object sender, EventArgs e)
{
// Kayıt Silme
arac(personDataSet);
DialogResult son;
son = MessageBox.Show("kayıtı silmek istiyormusunuz...", "silme kontrolu",
MessageBoxButtons.YesNo);
if (son == DialogResult.Yes)
{
sonra.RemoveAt(sonra.Position);
adresTableAdapter.Update(personDataSet.adres);
}
else
{ MessageBox.Show("kayıt silinmedi..."); }
}
private void button6_Click(object sender, EventArgs e)
{
// database kayıt
arac(personDataSet);
sonra.EndCurrentEdit(); // dataset'e (ram) kayıt
adresTableAdapter.Update(personDataSet.adres);
// database'e kayıt
MessageBox.Show("Database kayıt yapıldı..");
}
private void button7_Click(object sender, EventArgs e)
{
// Arama
int t = 0, b = 0;
arac(personDataSet);
105
Visual Studio 2010 .Net C#
foreach (DataRow satir in personDataSet.adres.Rows)
{
if (satir[0].ToString() == textBox6.Text)
{
sonra.Position = t; b = 1;
return; //for'dan cık
}
t++;
}
if (b == 0) MessageBox.Show("kayıt bulunamadı...");
}
private void button8_Click(object sender, EventArgs e)
{
// Kayıt giriş başlama
arac(personDataSet);
sonra.AddNew();
textBox1.Focus();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// form cıkışta otomatik database'e kayıt
arac(personDataSet);
sonra.EndCurrentEdit(); // datase'e(ram) kayıt
adresTableAdapter.Update(personDataSet.adres); // database'e kayıt
}
private void button9_Click(object sender, EventArgs e)
{
Application.Exit();
}
106
Visual Studio 2010 .Net C#
SQL cümleler ile Access erişimi
Visual c# projesi yaratılır.
Button ,Label ve Texbox tık tık yaparak veya sürükleyerek veya bir kez sayfaya
getirdikten sonra copy-paste ile getiririz.
107
Visual Studio 2010 .Net C#
Label, button objelerin özelliklerden ismini değiştiririz.
Butonlara tek tek tıklanarak kodlama yapılır.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; // yeni eklendi
namespace access_sql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// alttaki uc satır eklendi
OleDbConnection baglan = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=d:\\c#_calis\\person.accdb");
OleDbCommand veri; // yazmada kullanıyoruz
OleDbDataReader oku; // okumada kullanıyoruz
108
Visual Studio 2010 .Net C#
private void temizleme()
{
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;
textBox4.Text = "";
textBox5.Text = "";
textBox1.Focus();
}
private void d_oku()
{
oku = veri.ExecuteReader();
// oku.Read(); sadece bu satırı kullanamayız.kayıt olmaz ise sorun verir.O yüzden while ile kullanırız.
int kont = 0;
while (oku.Read())
{
kont = 1;
textBox1.Text = oku["nosu"].ToString();
textBox2.Text = oku["adi"].ToString();
textBox3.Text = oku["soyadi"].ToString();
textBox4.Text = oku["sehir"].ToString();
textBox5.Text = oku["tel"].ToString();
}
if (kont == 0) MessageBox.Show("kayıt yoktur ...");
oku.Close();
baglan.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button10_Click(object sender, EventArgs e)
{
// temizleme
temizleme();
}
private void button1_Click(object sender, EventArgs e)
{
// ilk kayıt
baglan.Open();
veri = new OleDbCommand("select top 1 nosu,adi,soyadi,sehir,tel from adres order by nosu asc ",
baglan);
d_oku();
}
private void button2_Click(object sender, EventArgs e)
109
Visual Studio 2010 .Net C#
{
// onceki kayıt
baglan.Open();
veri = new OleDbCommand("select top 1 nosu,adi,soyadi,sehir,tel from adres where nosu<'" +
textBox1.Text + "' order by nosu desc", baglan);
d_oku();
}
private void button3_Click(object sender, EventArgs e)
{
// sonraki kayıt
baglan.Open();
veri = new OleDbCommand("select top 1 nosu,adi,soyadi,sehir,tel from adres where nosu>'" +
textBox1.Text + "' ", baglan);
d_oku();
}
private void button5_Click(object sender, EventArgs e)
{
// son kayıt
baglan.Open();
veri = new OleDbCommand("select top 1 nosu,adi,soyadi,sehir,tel from adres order by nosu desc ",
baglan);
d_oku();
}
private void button4_Click(object sender, EventArgs e)
{
// arama
baglan.Open();
veri = new OleDbCommand("select nosu,adi,soyadi,sehir,tel from adres where nosu='" + textBox1.Text +
"'", baglan);
d_oku();
}
private void button7_Click(object sender, EventArgs e)
{
// kayıt etme
//veritabanına veri eklerken insert sql cümlesi yazıcaz.
baglan.Open();//öncelikle bağlantımızı açıyoruz.
veri = new OleDbCommand("insert into adres values('" + textBox1.Text + "', '" + textBox2.Text + "' , '" +
textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')", baglan);
veri.ExecuteNonQuery();
temizleme();
baglan.Close();
}
private void button8_Click(object sender, EventArgs e)
{
// degiştirme
baglan.Open();
veri = new OleDbCommand("update adres set nosu='" + textBox1.Text + "',adi='" + textBox2.Text +
"',soyadi='" + textBox3.Text + "',sehir='" + textBox4.Text + "',tel='" + textBox5.Text + "' where
nosu='" + textBox1.Text + "'", baglan);
veri.ExecuteNonQuery();
110
Visual Studio 2010 .Net C#
temizleme();
MessageBox.Show(" Değiştirme yapıldı..");
baglan.Close();
}
private void button6_Click(object sender, EventArgs e)
{
// kayıt silme
DialogResult son;
son = MessageBox.Show("kayıtı silmek istiyormusunuz...", "silme kontrolu", MessageBoxButtons.YesNo);
if (son == DialogResult.Yes)
{
baglan.Open();
veri = new OleDbCommand("delete from adres where nosu='" + textBox1.Text + "' ", baglan);
veri.ExecuteNonQuery();
temizleme();
MessageBox.Show(" Kayıt Silindi...");
baglan.Close();
}
else
{ MessageBox.Show("kayıt silinmedi..."); }
}
private void button9_Click(object sender, EventArgs e)
{
// Cıkıs
Application.Exit();
}
}
}
Microsoft Sql işlemleri
Sqlserver 2003,2005,2008 sürümleri vardır.
SQL Server 2000 Evaluation Edition: 120 gün kısıtlı kullanıma sahip update edilemeyen
(service pack yüklenemeyen) deneme amaçlı kullanılan sürümdür.
SQL Server 2000 Developer Edition: Geliştirme amaçlı kullanılan üründür. Genelde
yazılım geliştiriciler tarafından kullanılır. Diğer sürümlerde bulunan tüm özelliklere sahiptir.
SQL Server 2000 Windows CE Edition: Pocet Pc’lerde kullanılan Windows CE işletim
sistemleri için geliştirilmiş sürümdür.
SQL Server 2000 Desktop Engine (Personal Edition): Maximun 2GB data boyutunu
destekleyen olap engine uygulamalarına ambarlık yapabilecek kapasitede olan aynı zamanda
maximum workgroup kullanıcılarını destekleyen sürümdür. Server dışındaki bilgisayarlarada
kurulabilir. Xp, Win98, WinMe gibi.
111
Visual Studio 2010 .Net C#
SQL Server 2000 Standart Edition: Windows NT-2000-2003 server family üzerine kurulan
bilir. Teorik olarak 1,048,516 TB. Data boyutunu destekler. 2 GB memory 4 CPU desteği
vardır.
SQL Server 2000 Enterprise Edition: Hepsini kapsar.Windows NT-2000-2003 server
family üzerine kurulan bilir Teorik olarak 1,048,516 TB. Data boyutunu destekler. Cluster
olarak krulabilir. 64 GB memory 32 CPU desteği vardır. Tabii ki bu destek işletim sistemi ile
ilgilidir.
SQL Server 2000 64-bit Edition: SQL Server 2000 serisinin en taze ürünüdür. Intel®
Itanium™- tabanlı serverlar üzerinde 64 bit işletim sistemine sahip serverlarda gerçek
performansına ulaşılır.
SQLserver 2008
SQL Server 2008 Enterprise :SQL Server 2008 Enterprise, kurumsal çevrimiçi işlem ve veri
ambarı uygulamalarının yüksek taleplerini karşılayan kapsamlı bir veri platformudur.
SQL Server 2008 Standard:SQL Server 2008 Standard departman uygulamalarını
çalıştırmak için sınıfının en iyisi kullanım ve yönetim kolaylığı sağlayan tam bir veri yönetimi
ve kurumsal zeka platformudur.
Özel Sürümler
SQL Server 2008 Workgroup :Şubeleri, güvenli uzaktan eşitleme ve yönetim özellikleri
sağlayan bu güvenilir veri yönetimi ve raporlama platformunda çalıştırılır.
SQL Server 2008 Web :Yüksek kullanılabilir Internet tarafı web hizmeti ortamlarıyla
yüksek düşük maliyetli, yüksek ölçekli, yüksek kullanılabilir web uygulamaları veya veri
barındırma çözümleri sağlanır.
SQL Server 2008 Developer: Sadece geliştirme, test ve gösterim amacıyla geliştirici başına
lisans verilen düşük maliyetli SQL Server 2008 Enterprise sürümü.
Ücretsiz Sürümler
SQL Server 2008 Express :Ücretsiz olarak yükleyebileceğiniz SQL Server 2008 Express,
masaüstü ve küçük sunucu uygulamalarını öğrenmek ve oluşturmak ve ISV'ler tarafından
dağıtım için idealdir.
SQL Server Compact 3.5 :Ücretsiz olarak yüklenebilen SQL Server Compact, geliştiricilerin
SQL Server'ı doğrudan uygulamalarına dahil etmesini sağlar ve tüm Microsoft Windows
112
Visual Studio 2010 .Net C#
platformlarındaki mobil aygıtlar, masaüstü sistemleri ve web istemcileri için arada bir
bağlanan ve bağımsız uygulamalar sağlar.
Bulut Hizmetleri
SQL Azure Veritabanı :Microsoft SQL Azure™ Veritabanı SQL Server teknolojilerini
kullanan bulut tabanlı bir ilişkisel veritabanı hizmetidir. Microsoft tarafından buluttan
barındırılan yüksek kullanılabilir, ölçeklendirilebilir, çok müşterili bir veritabanı hizmetidir.
SQL Azure Veritabanı, çoklu veritabanlarının kolay bir şekilde sağlanmasına ve
uygulanmasına olanak verir. Geliştiricilerin herhangi bir yazılımı kurması, ayarlaması, yama
uygulaması veya yönetmesi gerekmez. Yüksek Kullanılabilirlik ve hata toleransı dahilidir ve
herhangi bir fiziksel yönetim gerektirmez. SQL Azure Veritabanı Transact-SQL (T-SQL)
destekler. Müşteriler T-SQL tabanlı benzer ilişkisel veri modeli ve mevcut programlama
araçları hakkındaki bilgilerini kullanabilir. SQL Azure Veritabanı, iki sürüm sağlar: Web
Edition ve Business Edition .
Microsoft Sql Server 2005 ve Client Management kurulumu
Microsoft SQL server2005 Express kurulumu
SQLEXPR.EXE --
Install
113
Visual Studio 2010 .Net C#
114
Visual Studio 2010 .Net C#
115
Visual Studio 2010 .Net C#
Microsoft SQL Client Management Kurulumu
SQLServer2005_SSMSEE.msi ----->
Install
116
Visual Studio 2010 .Net C#
Eklenmiş
olan
Microsoft
Sql2005
programları
Microsoft SQL Server’a Giriş
SQL Server
Management
Studio
Express ile
girilir.
117
Visual Studio 2010 .Net C#
118
Visual Studio 2010 .Net C#
Microsoft SQL Database,table oluşturma
֠ Sql Server Management Studio Express programına, Windows Vista ve Windows7’de
direk giriş yapılmaz. Eğer yapılırsa Database, table oluşturamayız, izin sorunu oluşur.Sağ
Mouse - yönetici modunda çalıştır olarak gireriz.
SQL Server
Management
Studio
Express ile
girilir.
Databases
üzerinde sağ
Mouse
tıklayarak
New Database
seçilir.
119
Visual Studio 2010 .Net C#
Yeni oluşacak
olan Database
ismini uretim
gibi veririz.
Microsoft SQL’de table oluşturma
SQL Server
Management
Studio
Express ile
girilir.
120
Visual Studio 2010 .Net C#
Table
oluşturma
-Table
oluşturmak
istediğimiz
Database’in
(Uretim gibi)
altında bulunan
Tables’a
tıklarız. Daha
sonra sağ
mouse ile New
Table seçeriz.
-nosu,adi,
soyadi gibi
değişken
isimlerini tek
tek yazarak
table
oluştururuz.
- Primary key
tanımı için nosu
üzerinde sağ
mouse tılayarak
Set primary
key seçeriz.
- Tanımlı
table’dan
cıkarken, table
ismini adres
olarak veririz.
121
Visual Studio 2010 .Net C#
Table
Designına
giriş
(değişken
tanımlarına)
Data girişi
. Sırasıyla
Uretim,
Tables ve
adres tıklanır
. adres
üzerinde sağ
mouse ile
Open table
seçilerek
veriler girilir.
Microsoft SQL
Server Veri
tabanı ve
Table isimleri
Veritabanı : Uretim
Table
: adres
122
Visual Studio 2010 .Net C#
Microsoft Sql ile kayıt işlemleri
Access’teki 1.yöntem,2.yöntem,3.yöntem ile aynısıdır.Sadece table secimi farklıdır.
Texbox’larda gösterme ve önceki, sonraki kayıtlara gecme’de ise table secimi ve kodlama
farklıdır. Kodlamada personDataSet yerine egitimDataSet kullanıyoruz.
Table secimi 1. Aşama :
Access 1. Yöntem:
Access 2. Yöntem:
123
Visual Studio 2010 .Net C#
Access 3. Yöntem :
Texbox’larda gösterme ve önceki, sonraki kayıtlara gecme :
124
Visual Studio 2010 .Net C#
Table secimi 2. Aşama :
125
Visual Studio 2010 .Net C#
Texbox’larda gösterme ve önceki, sonraki kayıtlara gecmede kodlama
access’deki personDataSet egitimDataSet olarak değişir.
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'egitimDataSet.adres' table. You can move, or remove it, as
needed.
this.adresTableAdapter.Fill(this.egitimDataSet.adres);
textBox1.DataBindings.Add("Text", egitimDataSet.adres, "nosu");
textBox2.DataBindings.Add("Text", egitimDataSet.adres, "adi");
textBox3.DataBindings.Add("Text", egitimDataSet.adres, "soyadi");
textBox4.DataBindings.Add("Text", egitimDataSet.adres, "sehir");
textBox5.DataBindings.Add("Text", egitimDataSet.adres, "tel");
}
private void button1_Click(object sender, EventArgs e)
{
// ilk kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
sonra.Position = 0;
}
private void button2_Click(object sender, EventArgs e)
{
//Önceki kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
if (sonra.Position <= 0)
{
MessageBox.Show("baska kayıt kalmadı.ilk kayıttasınız");
126
Visual Studio 2010 .Net C#
}
else
{ sonra.Position -= 1; }
}
private void button3_Click(object sender, EventArgs e)
{
// Sonraki kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
if (sonra.Position >= sonra.Count - 1)
{
MessageBox.Show("baska kayıt kalmadı.Son kayıttasınız");
}
else
{ sonra.Position += 1; }
}
private void button4_Click(object sender, EventArgs e)
{
// En son kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
sonra.Position = sonra.Count - 1;
}
private void button5_Click(object sender, EventArgs e)
{
// Kayıt Silme
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
DialogResult son;
son = MessageBox.Show("kayıtı silmek istiyormusunuz...", "silme kontrolu", MessageBoxButtons.YesNo);
if (son == DialogResult.Yes)
{
sonra.RemoveAt(sonra.Position);
adresTableAdapter.Update(egitimDataSet.adres);
}
else
{ MessageBox.Show("kayıt silinmedi..."); }
}
private void button6_Click(object sender, EventArgs e)
{
// database kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
sonra.EndCurrentEdit(); // dataset'e (ram) kayıt
adresTableAdapter.Update(egitimDataSet.adres); // database'e kayıt
MessageBox.Show("Database kayıt yapıldı..");
}
private void button7_Click(object sender, EventArgs e)
{
// Arama
int t = 0, b = 0;
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
foreach (DataRow satir in egitimDataSet.adres.Rows)
{
if (Convert.ToInt32(satir[0].ToString()) == Convert.ToInt32(textBox6.Text))
127
Visual Studio 2010 .Net C#
{
sonra.Position = t; b = 1;
return; //for'dan cık
}
t++;
}
if (b == 0) MessageBox.Show("kayıt bulunamadı...");
}
private void button8_Click(object sender, EventArgs e)
{
// Kayıt giriş başlama
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
sonra.AddNew();
textBox1.Focus();
}
private void button9_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// form cıkışta otomatik database'e kayıt
CurrencyManager sonra = (CurrencyManager)BindingContext[egitimDataSet.adres];
sonra.EndCurrentEdit(); // dataset'e(ram) kayıt
adresTableAdapter.Update(egitimDataSet.adres); // database'e kayıt
}
SQL cümleler ile Microsoft Sql erişimi
Access ile Microsoft SQL arasında kod farklılıkları
Access
Microsoft SQL
using System.Data.OleDb;
using System.Data.SqlClient;
OleDbConnection
OleDbCommand
OleDbDataReader
SqlConnection
SqlCommand
sqlDataReader
Access :
OleDbConnection baglan = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=d:\\c#_calis\\person.accdb");
Microsoft Sql :
SqlConnection baglan = new SqlConnection(@"Data Source=VMBILGISAYAR\SQLEXPRESS3;Initial
Catalog=egitim;Integrated Security=True");
128
Visual Studio 2010 .Net C#
֠
Access veya M.sql’de yukardaki kırmızı renkli bağlantı kodlarını Internet’ten bulabiliriz veya
Data - Add new data source ‘a denemek için girerek , en sonunda oluşan connection String
kodunu copy-paste ile alırız.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; // Microsoft SQL için eklendi
namespace access_sql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// alttaki iki satır eklendi
// catalog - database ismi(egitim), Data source - Çalışan Microsoft SQL ismi(
VMBILGISAYAR\SQLEXPRESS3 )
SqlConnection baglan = new SqlConnection(@"Data Source=VMBILGISAYAR\SQLEXPRESS3;Initial
Catalog=egitim;Integrated Security=True");
SqlCommand veri; // yazmada kullanıyoruz
SqlDataReader oku; // okumada kullanıyoruz
private void temizleme()
129
Visual Studio 2010 .Net C#
{
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;
textBox4.Text = "";
textBox5.Text = "";
textBox1.Focus();
}
private void d_oku()
{
oku = veri.ExecuteReader();
// oku.Read(); sadece bu satırı kullanamayız.kayıt olmaz ise sorun verir.O yüzden while ile kullanırız.
int kont = 0;
while (oku.Read())
{
kont = 1;
textBox1.Text = oku["nosu"].ToString();
textBox2.Text = oku["adi"].ToString();
textBox3.Text = oku["soyadi"].ToString();
textBox4.Text = oku["sehir"].ToString();
textBox5.Text = oku["tel"].ToString();
}
if (kont == 0) MessageBox.Show("kayıt yoktur ...");
oku.Close();
baglan.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button10_Click(object sender, EventArgs e)
{
// temizleme
temizleme();
}
private void button1_Click(object sender, EventArgs e)
{
// ilk kayıt
baglan.Open();
veri = new SqlCommand("select top 1 nosu,adi,soyadi,sehir,tel from adres order by nosu asc ", baglan);
d_oku();
}
private void button2_Click(object sender, EventArgs e)
{
// onceki kayıt
baglan.Open();
130
Visual Studio 2010 .Net C#
veri = new SqlCommand("select top 1 nosu,adi,soyadi,sehir,tel from adres where nosu<'" +
textBox1.Text + "' order by nosu desc", baglan);
d_oku();
}
private void button3_Click(object sender, EventArgs e)
{
// sonraki kayıt
baglan.Open();
veri = new SqlCommand("select top 1 nosu,adi,soyadi,sehir,tel from adres where nosu>'" +
textBox1.Text + "' ", baglan);
d_oku();
}
private void button5_Click(object sender, EventArgs e)
{
// son kayıt
baglan.Open();
veri = new SqlCommand("select top 1 nosu,adi,soyadi,sehir,tel from adres order by nosu desc ",
baglan);
d_oku();
}
private void button4_Click(object sender, EventArgs e)
{
// arama
baglan.Open();
veri = new SqlCommand("select nosu,adi,soyadi,sehir,tel from adres where nosu='" + textBox1.Text + "'",
baglan);
d_oku();
}
private void button7_Click(object sender, EventArgs e)
{
// kayıt etme
//veritabanına veri eklerken insert sql cümlesi yazıcaz.
baglan.Open();//öncelikle bağlantımızı açıyoruz.
veri = new SqlCommand("insert into adres values('" + textBox1.Text + "', '" + textBox2.Text + "' , '" +
textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')", baglan);
veri.ExecuteNonQuery();
temizleme();
baglan.Close();
}
private void button8_Click(object sender, EventArgs e)
{
// degiştirme
baglan.Open();
veri = new SqlCommand("update adres set nosu='" + textBox1.Text + "',adi='" + textBox2.Text +
"',soyadi='" + textBox3.Text + "',sehir='" + textBox4.Text + "',tel='" + textBox5.Text + "' where nosu='" +
textBox1.Text + "'", baglan);
veri.ExecuteNonQuery();
temizleme();
MessageBox.Show(" Değiştirme yapıldı..");
baglan.Close();
131
Visual Studio 2010 .Net C#
}
private void button6_Click(object sender, EventArgs e)
{
// kayıt silme
DialogResult son;
son = MessageBox.Show("kayıtı silmek istiyormusunuz...", "silme kontrolu", MessageBoxButtons.YesNo);
if (son == DialogResult.Yes)
{
baglan.Open();
veri = new SqlCommand("delete from adres where nosu='" + textBox1.Text + "' ", baglan);
veri.ExecuteNonQuery();
temizleme();
MessageBox.Show(" Kayıt Silindi...");
baglan.Close();
}
else
{ MessageBox.Show("kayıt silinmedi..."); }
}
private void button9_Click(object sender, EventArgs e)
{
// Cıkıs
Application.Exit();
}
}
}
132
Visual Studio 2010 .Net C#
Console Đşlemleri
133
Visual Studio 2010 .Net C#
static void Main(string[] args)
{
string isim,adres;
Console.WriteLine("kayıt sistemi \n\n ismini giriniz ..:");
isim=Console.ReadLine();
Console.WriteLine("adresini giriniz ..:");
adres=Console.ReadLine();
Console.WriteLine("isminiz ..:"+isim+"\n"+"adres..:"+adres+" cıkıs için Enter");
Console.ReadLine();
}
Uygulama : Sınıf gecme hesaplama
static void Main(string[] args)
{
Console.WriteLine("degerlendirme yapacakmısınız (E/H)");
string deger;
deger=Console.ReadLine();
if(deger=="E")
{
degerlendir();
}
}
private static void degerlendir()
{
int vize1,vize2,final;
double sonuc;
Console.WriteLine("birinci vize notu ..:");
vize1=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("ikinci vize notu ..:");
vize2=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("final notu ..:");
final=Convert.ToInt32(Console.ReadLine());
sonuc=(vize1+vize2)*0.2+final*0.6;
if(sonuc>=50)
{
Console.WriteLine("sınıfı gectiniz..");
}
else
{
Console.WriteLine("sınıfı gecemediniz..");
}
Console.WriteLine("not ortalaması..:"+sonuc.ToString());
Console.WriteLine("degerlendirme yapacakmısınız (E/H)");
string deger;
deger=Console.ReadLine();
if(deger=="E")
{
degerlendir();
}
}
134
Visual Studio 2010 .Net C#
Uygulama : Access dosyadan kayıt okuma
using System;
using System.Data; // ekleme yapıldı
using System.Data.OleDb; // ekleme yapıldı
“
“
“
“
static void Main(string[] args)
{
string baglanti = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=d:\\c#_calis\\person.accdb";
DataSet ds_yeni = new DataSet();
OleDbConnection con_yeni = new OleDbConnection(baglanti);
OleDbDataAdapter da_yeni = new OleDbDataAdapter("select * from adres", con_yeni);
da_yeni.Fill(ds_yeni, "adres");
Console.WriteLine(" tüm kayıtlar ");
Console.WriteLine("--------------------------");
foreach (DataRow satir in ds_yeni.Tables[0].Rows)
{
Console.WriteLine(satir[1].ToString() + " " + satir[2].ToString() + " " + satir[3].ToString());
}
Console.ReadLine();
}
135
Visual Studio 2010 .Net C#
Raporlama ( Crystal Reports )
Access’dan rapor oluşturma
1.Yöntem: Direk rapor oluşturma
136
Visual Studio 2010 .Net C#
137
Visual Studio 2010 .Net C#
Crystalreport1.rpt şeklinde Rapor oluşur. Main report olarak kod kısmını, Main Report
Previev olarak çalışmış halini görebiliriz.
Project -- add new item - Window form ile form2 ekleriz.
Form2 ‘ye bir buton ekleriz ve ismini rapor şeklinde değiştiririz.
138
Visual Studio 2010 .Net C#
Rapor butona cift tıklayarak aşagıdaki kodu yazarız.
Form1 yeni = new Form1();
yeni.Show();
139
Visual Studio 2010 .Net C#
İlk form Form1 yaratıldıgı için onu değiştirmeliyiz. Yani başlangıc formunu Form2
yaparız.Program.cs’ye tıklayarak form1’i form2 yaparız.
Şimdi F5 veya Debug - start debugging veya çalıştırma iconuna
tıklayarak çalıştırırız.
140
Visual Studio 2010 .Net C#
2.Yöntem: Form üzerinde sonradan rapor oluşturma
C# ’a girilerek form1 oluşturulur .
Sonradan Crystal report eklemek ( toolbox’a icon olarak gözükmesi için ) için
.net framework4 clint profile’ın .net framework4 olarak değiştirilmesi gerekir.
141
Visual Studio 2010 .Net C#
Form2 oluşturulur.
Crystal report oluşturulur.
142
Visual Studio 2010 .Net C#
143
Visual Studio 2010 .Net C#
Crystalreport1.rpt şeklinde Rapor oluşur. Main report olarak kod kısmını, Main Report
Previev olarak çalışmış halini görebiliriz.
Form2’ye tıklar. Toolbox’tan Crystal report iconu, çift tıklayarak veya sürükleyerek form2
üzerinde rapor oluştururuz.
144
Visual Studio 2010 .Net C#
Form2 üzerinde crystal report secilerek özelliklerden report source ‘a crystalreport1
secilir.
Form1 seceriz( Eğer form1 gizli ise Solution explorer’dan form1.cs tıklayarak form1
sayfasını getiririz ) .Form1 üzerinde bir buton oluştururuz ve button’un ismini rapor olarak
değiştiririz. Butona cift tıklayarak kodlama yaparız.
145
Visual Studio 2010 .Net C#
Form2 yeni = new Form2();
yeni.Show();
146
Visual Studio 2010 .Net C#
F5 veya Debug - start debugging veya çalıştırma iconuna
çalıştırırız.
tıklayarak
147
Visual Studio 2010 .Net C#
Microsoft SQL’den rapor oluşturma
Access’den rapor oluşturma yöntemi ile aynıdır.Sadece Erişim olarak sql server kullanırız.
148
Visual Studio 2010 .Net C#
Şartlı
artlı Raporlar
Access’den belirli kayıt raporu oluşturma
C# ’a girilerek form1 oluşturulur .
Sonradan Crystal report eklemek ( toolbox’a icon olarak gözükmesi için ) için
.net framework4 clint profile’ın .net framework4 olarak değiştirilmesi gerekir.
149
Visual Studio 2010 .Net C#
Form2 oluşturulur.
Crystal report oluşturulur.
150
Visual Studio 2010 .Net C#
Hatırlatma :
select * from adres where nosu
="{?ykod}"
select * from adres where nosu
like "{?ykod}"
- noyu 100 veya ,200 gibi tam gireriz.
- noyu 100 veya 1% veya 10% girebiliriz. 1 ile veya 10
ile başlayanları listeler.
select * from adres where nosu like "{?ykod}"&"%" -- 100, 1 , 10 verebiliriz. 100 veya 1 veya 10 ile
başlayanları listeler. Boş girersek hepsini listeler.
151
Visual Studio 2010 .Net C#
152
Visual Studio 2010 .Net C#
Crystalreport1.rpt şeklinde Rapor oluşur. Main report olarak kod kısmını, Main Report
Previev olarak çalışmış halini görebiliriz.
Form2’ye tıklar. Toolbox’tan Crystal report iconu, çift tıklayarak veya sürükleyerek form2
üzerinde rapor oluştururuz.
153
Visual Studio 2010 .Net C#
Form2 üzerinde crystal report secilerek özelliklerden report source ‘a crystalreport1
secilir.
Form1 seceriz( Eğer form1 gizli ise Solution explorer’dan form1.cs tıklayarak form1
sayfasını getiririz ) .Form1 üzerinde bir TextBox ve bir buton oluştururuz ve button’un
ismini rapor olarak değiştiririz. Butona cift tıklayarak kodlama yaparız.
154
Visual Studio 2010 .Net C#
public static string kodx;
Form2 yeni=new Form2();
kodx=textBox1.Text;
yeni.Show();
155
Visual Studio 2010 .Net C#
Form2 sayfasını secer, çift tıklar ve aşagıdaki kodlamayı yaparız.
CrystalReport1 rapor = new CrystalReport1();
CrystalDecisions.Shared.ParameterValues parametre = new
CrystalDecisions.Shared.ParameterValues();
CrystalDecisions.Shared.ParameterDiscreteValue deger = new
CrystalDecisions.Shared.ParameterDiscreteValue();
deger.Value = Form1.kodx;
parametre.Add(deger);
rapor.DataDefinition.ParameterFields["ykod"].ApplyCurrentValues(parametre);
crystalReportViewer1.ReportSource = rapor;
F5 veya Debug - start debugging veya çalıştırma iconuna
çalıştırırız.
tıklayarak
156
Visual Studio 2010 .Net C#
Microsoft SQL’den belirli kayıt raporu oluşturma
Access’den rapor oluşturma yöntemi ile aynıdır.Sadece Erişim olarak sql server kullanırız.
1.yöntem : Komut satırı ile
157
Visual Studio 2010 .Net C#
Hatırlatma :
Access’de cift tırnak ( “ ) , sql’de tek tırnak ( ‘ ) kullanıyoruz.Access ve Sql’de aşagıdaki satırları kopya
ile kullanmayalım.Kullanırsakta cift veya tek tırnagı orada mutlaka yeniden yazalım.
select * from adres where nosu
=’{?ykod}’
select * from adres where nosu
like ‘{?ykod}’
- noyu 100 veya ,200 gibi tam gireriz.
- noyu 100% veya 1% veya 10% girebiliriz. 100 ile 1 ile
veya 10 ile başlayanları listele.Sadece 100 yazamayız.
select * from adres where nosu like ‘{?ykod}%’ -- 100, 1 , 10 verebiliriz. 100 veya 1 veya 10 ile
başlayanları listele. Boş girersek hepsini listeler.
158
Visual Studio 2010 .Net C#
2.yöntem : Store procedure kullanımı ile
Microsoft Sql Server’da sec isminde bir store procedure oluştururuz.
CREATE PROCEDURE sec @ykod varchar(25) as
select * from adres where nosu=@ykod
GO
Hatırlatma:
where nosu=@ykod -- 100,200,300 gibi tam no listelenir.
where nosu like @ykod - 100%,1% girilmelidir.100 ile ,1 ile başlayanlar listelenir.
where nosu like @ykod+'%' - boş girilirse hepsi, 1girilirse, 1 ile başlayanlar ,100 girilirse
100 ile başlayanlar.
Microsoft SQL Server’a girilir.
Sql Server Management Studio Express programına, Windows Vista ve Windows7’de
direk giriş yapılmaz. Eğer yapılırsa Database, table oluşturamayız, izin sorunu oluşur.Sağ
Mouse - yönetici modunda çalıştır olarak gireriz.
159
Visual Studio 2010 .Net C#
Yazdıgımız procedure önce sağ Mouse -- Save sec.sql
(execute ) yani sec procedure oluşturmuş oluruz.
gibi saklarız. Sonra çalıştırırız
Sakladıgımız procedure sql dosyasını daha sonra istersek kullanabiliriz. O dosyayı görme.
Procedure oluşturma
160
Visual Studio 2010 .Net C#
Oluşan procedure dosyasını görme. Programa bir kez girip cıktıktan sonra veya refresh
ederek görebiliriz.
•
Access’den rapor oluşturma yöntemi ile aynıdır.Sadece Erişim olarak sql server
kullanırız.
161
Visual Studio 2010 .Net C#
•
Form2 kod sayfasında [“@ykod”] olarak kullanırız.
162
Visual Studio 2010 .Net C#
CrystalReport1 rapor = new CrystalReport1();
CrystalDecisions.Shared.ParameterValues parametre = new
CrystalDecisions.Shared.ParameterValues();
CrystalDecisions.Shared.ParameterDiscreteValue deger = new
CrystalDecisions.Shared.ParameterDiscreteValue();
deger.Value = Form1.kodx;
parametre.Add(deger);
["@ykod"].ApplyCurrentValues(parametre);
rapor.DataDefinition.ParameterFields
crystalReportViewer1.ReportSource = rapor;
163
Visual Studio 2010 .Net C#
Cift şartlı kullanma
Table erişimi yapılırken -
select * from adres where nosu=”{?ykod}” and adi=”{?yadi}” -- access
select * from adres where nosu=’{?ykod}’ and adi=’{?yadi}’
-- Microsoft SQL
Not: yukardaki kodlar copy ile programa alınırsa cift veya tek tırnak yeniden
yazılmalıdır.Uyumsuzluk gösteriyor.
Form değişiklik --
iki textbox eklenir.nosu ve adı için
164
Visual Studio 2010 .Net C#
Form2’de kod değişiklik ---
CrystalReport1 rapor = new CrystalReport1();
CrystalDecisions.Shared.ParameterValues parametre = new
CrystalDecisions.Shared.ParameterValues();
CrystalDecisions.Shared.ParameterDiscreteValue deger = new
CrystalDecisions.Shared.ParameterDiscreteValue();
deger.Value = Form1.kodx;
parametre.Add(deger);
rapor.DataDefinition.ParameterFields["ykod"].ApplyCurrentValues(parametre);
deger.Value = Form1.adx;
parametre.Add(deger);
rapor.DataDefinition.ParameterFields["yadi"].ApplyCurrentValues(parametre);
crystalReportViewer1.ReportSource = rapor;
Form1 botton kodda degişiklik -
public static string kodx;
public static string adx;
Form2 yeni=new Form2();
kodx=textBox1.Text;
adx=textBox2.Text;
yeni.Show();
165
Visual Studio 2010 .Net C#
Raporda işlem yapma
•
Başlık verme
Toolbox’tan TextObject iconu sürkleyerek sayfa üst bilgisine bırakılır. Sağa sola taşırız.
Properties’ten rengini ve fontunu veya üst cubuktan değiştirebiliriz.
166
Visual Studio 2010 .Net C#
•
String deger olan gun_say ve gun_ucret’i integer’a cevirme
1) Field Explorer tıklanır.
2) Formula Fields - sağ Mouse - New secilerek
ucret ismi verilir.
167
Visual Studio 2010 .Net C#
3) toNumber formulu yazılarak kaydet ile saklanır.ucret değişkenimiz olmuş oldu.Rapor
alanlarında ucret degişkenini rapor icerisine sürükleyerek veya cift tıklayarak getirebiliriz.
4) aynı yöntem ile string deger olan gun_say değişkenini integer haline say isminde getiririz.
168
Visual Studio 2010 .Net C#
5) ucret ve say ile carpım yapılarak brut değişkeni oluştururuz.
6) brut değişkeni sayfa içerine sürüklenir.Acıklama olarak üste brut yazısı cıkar .İstersek
Text Object sürükleyerek’de brut acıklaması yazdırabiliriz.Textobject sürükleyerek bir alan
oluşturuz ve icerisine brut yazarız.
169
Visual Studio 2010 .Net C#
7) En alta brut degerlerini tbrut alanına toplatalım.
8) tbrut degerini sayfa icerisine sürükleyelim.
9) F5 ile raporu çalıştırırız.
170
Visual Studio 2010 .Net C#
171
Visual Studio 2010 .Net C#
CrystalReport’un Görünümünü değiştirme
172

Benzer belgeler

toplama_donguler_ile_03_10_2015

toplama_donguler_ile_03_10_2015 Solution : toplama_donguler_ile Proje : toplama_for_dongusu_ile

Detaylı

Görsel Programlama Ders 9

Görsel Programlama Ders 9 System.Diagnostics.Process.Start("shutdown", "-f -s"); // Sistemi Kapat (-f arkaplanda çalışan uygulamaları kapat, -s 30 sn içinde sistemi kapat)

Detaylı

Form1 Form2 Form3 Form4

Form1 Form2 Form3 Form4 MessageBox.Show("Kayıt Silindi", "İşlem Tamam", MessageBoxButtons.OK, MessageBoxIcon.Information); txtGider.Clear(); txtMiktar.Clear(); txtAciklama.Clear(); Goster();

Detaylı

c# ile seri port, grafik, excel işlemleri

c# ile seri port, grafik, excel işlemleri public static string adi_soyadi; public static string adresi; public static int yasi; public static bool medeni_hal; public static string meslegi; public static long maasi; public const int sabit=1...

Detaylı

Untitled

Untitled C#’da Visual basic6.0 daki gibi bir bilgi giriş fonksiyonu yoktur. Fakat bu fonsiyonu Visual

Detaylı