Programlama yapalım ve Öğrenelim. - Visual C# .NET Örnek Kodları
  Ana Sayfa
  .NET Eğitim Notları
  Visual C# .NET Örnek Kodları
  VisualBasic.NET Örnek Kodları
  J# Örnekleri
  ASP.NET Örnek Kodları
  Delphi Eğitim
  İletişim
#Kodları böyle alt alta yazıyorum zamandan kazanasınız diye.
1.Kaç tane 5,10,50,50 lik para var bulalım.

ilk olarak forma 4 adet TExtBox ekleyin ...
textbaox1 in adını para olarak değiştirin..
2. text 100 ler
3. text 50 ler
4. text 10 lar
5. text 5  ler
6. text 1 ler
basamağıdır...
Arır adında bir class oluşturuyorum...
ve içinde :

public class ayır
    {
   
      
       int Para
       {
           get { return this.paramız; }
           set { this.paramız = value; }
       }

       public void gelenPara(int GPara)
       {
           this.paramız = GPara;
           ParaAyırYuzluk(this.paramız);
       }
     void ParaAyırYuzluk(int PARA)
       {
          sonuc[0] = PARA / 100;
          ParaAyırEllilik(this.paramız - (sonuc[0]*100));
       }
      void ParaAyırEllilik(int PARA)
      {
          sonuc[1] = PARA / 50;
          ParaAyırOnluk(this.paramız - (sonuc[0] * 100 + sonuc[1] * 50));
      }

      void ParaAyırOnluk(int PARA)
      {
          sonuc[2] = PARA / 10;
          ParaAyırBeslik(this.paramız - (sonuc[0] * 100 + sonuc[1] * 50 + sonuc[2] * 10));
      }
      void ParaAyırBeslik(int PARA)
      {
          sonuc[3] = PARA / 5;
          ParaAyırBirlik(this.paramız - (sonuc[0] * 100 + sonuc[1] * 50 + sonuc[2] * 10 + sonuc[3] *5));
      }
      void ParaAyırBirlik(int PARA)
      {
          sonuc[4] = PARA / 1;
      }

       public int[] sonuc = new int[5];
       private int paramız;
    }

tanımlıyorumm...  VE ANA PROGRAMA GELDiğimizde ben button nesnesinle gerçekleştirdim ,sizde istediğiniz gibi yapabilirsiniz


private void button1_Click(object sender, EventArgs e)
        { int gpara;
        textBox2.Text = "";
        textBox3.Text = "";
        textBox4.Text = "";
        textBox5.Text = "";
        textBox6.Text = "";
        try
        {
            gpara = int.Parse(para.Text);
            ayır AYR = new ayır();
            AYR.gelenPara(gpara);
            textBox2.Text = AYR.sonuc[0].ToString();
            textBox3.Text = AYR.sonuc[1].ToString();
            textBox4.Text = AYR.sonuc[2].ToString();
            textBox5.Text = AYR.sonuc[3].ToString();
            textBox6.Text = AYR.sonuc[4].ToString();
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
        }


2.İmaj boyutlandırma
public System.Drawing.Bitmap CreateThumbnail(System.IO.Stream lcStream, int lnWidth, int lnHeight)
{
   System.Drawing.Bitmap bmpOut = null;
   try
   {
      System.Drawing.Bitmap loBMP = new System.Drawing.Bitmap(lcStream);
      System.Drawing.Imaging.ImageFormat loFormat = loBMP.RawFormat;
      decimal lnRatio;
      int lnNewWidth = 0;
      int lnNewHeight = 0;

      if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
         return loBMP;
      if (loBMP.Width > loBMP.Height)
      {
         lnRatio = (decimal)lnWidth / loBMP.Width;
         lnNewWidth = lnWidth;

         decimal lnTemp = loBMP.Height * lnRatio;
         lnNewHeight = (int)lnTemp;
      }
      else
      {
         lnRatio = ( decimal)lnHeight / loBMP.Height;
         lnNewHeight = lnHeight;>

         decimal lnTemp = loBMP.Width * lnRatio;
         lnNewWidth = (int)lnTemp;
      }

      bmpOut = new System.Drawing.Bitmap(lnNewWidth, lnNewHeight);
      System.Drawing.Graphics g = Graphics.FromImage(bmpOut);
      g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
      g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
      g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);>
      loBMP.Dispose();
   }
    catch
   {
      return null;
   }
   

   return bmpOut;
}

3.C# İle App_Data İçindeki Access'e Kayıt Ekleme
protected void Kaydet_Click(object sender, EventArgs e)
    {

        OleDbConnection baglanti = new OleDbConnection();
        OleDbCommand komut = new OleDbCommand();
        string veritabani;
        string sorgu;
        int kayitekle = new int();

        veritabani = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("App_Data/veritabanim.mdb");
        baglanti = new OleDbConnection(veritabani);
        baglanti.Open();
        sorgu = "insert into ogrenciler(tcno,adi,soyadi) values('" + ogrencino.Text + "','" + adiniz.Text + "','" + soyadiniz.Text + "')";
        komut = new OleDbCommand(sorgu, baglanti);
        kayitekle = komut.ExecuteNonQuery();
        baglanti.Close();
    }

4.Kaynak tablodan alınan verilerin başka bir tabloya kayıt editmesi...
        protected void ddlBrmSetBas_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateStKartBrmSet();
        }

        private void UpdateStKartBrmSet()
        {
            pv.strSQL = "Select * From BrmSetDet Where FirmaNr=" + Convert.ToString(pv.actComp) + " And BrmSetNr=" + ddlBrmSetBas.SelectedValue;
            OleDbCommand BrmSetDetCmd = new OleDbCommand(pv.strSQL, pv.myC);
            pv.myC.Open();
            OleDbDataReader BrmSetDetRdr = BrmSetDetCmd.ExecuteReader();
            DeleteStKartBrmSet(pv.actComp, Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("StNr")));
            try
            {
                while (BrmSetDetRdr.Read())
                {
                    pv.strSQL = "INSERT INTO StKartBrmSet" +
                        /*1*/"(FirmaNr, StNr, BrmSetNr, SatirNr, DetayKodu, " +
                        /*2*/"DetayAdi, KatSayi1, KatSayi2, OzelKod, YetkiKodu, " +
                        /*3*/"En, EnRef, Boy, BoyRef, Yukseklik, " +
                        /*4*/"YukseklikRef, Alan, AlanRef, NetHacim, NetHacimRef, " +
                        /*5*/"BurutHacim, BurutHacimRef, NetAgirlik, NetAgirlikRef, BurutAgirlik, " +
                        /*6*/"BurutAgirlikRef, BarKod1, BarKod2, BarKod3, BirimliBarKod, " +
                        /*7*/"KUser, KTarih, DUser, DTarih)" +
                             "VALUES(" +
                        /*1*/Convert.ToString(pv.actComp) + "," + HttpContext.Current.Request.QueryString.Get("StNr") + "," + BrmSetDetRdr["BrmSetNr"].ToString() + "," + dmmy.GetLastStKartBrmSetSatirNr(Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("StNr")), Convert.ToInt32(BrmSetDetRdr["BrmSetNr"].ToString())) + ",'" + BrmSetDetRdr["DetayKodu"].ToString().Trim() + "','" +
                        /*2*/BrmSetDetRdr["DetayAdi"].ToString().Trim() + "',1,1,'',''," +
                        /*3*/"0,0,0,0,0," +
                        /*4*/"0,0,0,0,0," +
                        /*5*/"0,0,0,0,0," +
                        /*6*/"0,'','','','','" +
                        /*7*/pv.actUCode + "','" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "','',0)";
                    OleDbCommand StKartBrmSetInsert = new OleDbCommand(pv.strSQL, pv.myC);
                    StKartBrmSetInsert.ExecuteNonQuery();
                }
                BrmSetDetRdr.Close();
                pv.myC.Close();
                GetStKartBrmSet();
            }
            catch (Exception Ex)
            {
                try
                {
                    //StKartBrmSetTransaction.Rollback();
                }
                catch
                {
                    //
                }
                Response.Redirect("../Public/ErrInf.aspx?ErrMsgId=101&ErrMsgDsc=" + Ex.Message.ToString());
            }
        }
5.
Bir tablodaki kaydın döngü ile başka bir tabloya aktarılması...
        protected void ddlBrmSetBas_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateStKartBrmSet();
        }

        private void UpdateStKartBrmSet()
        {
            pv.strSQL = "Select * From BrmSetDet Where FirmaNr=" + Convert.ToString(pv.actComp) + " And BrmSetNr=" + ddlBrmSetBas.SelectedValue;
            OleDbCommand BrmSetDetCmd = new OleDbCommand(pv.strSQL, pv.myC);
            pv.myC.Open();
            OleDbDataReader BrmSetDetRdr = BrmSetDetCmd.ExecuteReader();
            DeleteStKartBrmSet(pv.actComp, Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("StNr")));
            try
            {
                while (BrmSetDetRdr.Read())
                {
                    pv.strSQL = "INSERT INTO StKartBrmSet" +
                        /*1*/"(FirmaNr, StNr, BrmSetNr, SatirNr, DetayKodu, " +
                        /*2*/"DetayAdi, KatSayi1, KatSayi2, OzelKod, YetkiKodu, " +
                        /*3*/"En, EnRef, Boy, BoyRef, Yukseklik, " +
                        /*4*/"YukseklikRef, Alan, AlanRef, NetHacim, NetHacimRef, " +
                        /*5*/"BurutHacim, BurutHacimRef, NetAgirlik, NetAgirlikRef, BurutAgirlik, " +
                        /*6*/"BurutAgirlikRef, BarKod1, BarKod2, BarKod3, BirimliBarKod, " +
                        /*7*/"KUser, KTarih, DUser, DTarih)" +
                             "VALUES(" +
                        /*1*/Convert.ToString(pv.actComp) + "," + HttpContext.Current.Request.QueryString.Get("StNr") + "," + BrmSetDetRdr["BrmSetNr"].ToString() + "," + dmmy.GetLastStKartBrmSetSatirNr(Convert.ToInt32(HttpContext.Current.Request.QueryString.Get("StNr")), Convert.ToInt32(BrmSetDetRdr["BrmSetNr"].ToString())) + ",'" + BrmSetDetRdr["DetayKodu"].ToString().Trim() + "','" +
                        /*2*/BrmSetDetRdr["DetayAdi"].ToString().Trim() + "',1,1,'',''," +
                        /*3*/"0,0,0,0,0," +
                        /*4*/"0,0,0,0,0," +
                        /*5*/"0,0,0,0,0," +
                        /*6*/"0,'','','','','" +
                        /*7*/pv.actUCode + "','" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "','',0)";
                    OleDbCommand StKartBrmSetInsert = new OleDbCommand(pv.strSQL, pv.myC);
                    StKartBrmSetInsert.ExecuteNonQuery();
                }
                BrmSetDetRdr.Close();
                pv.myC.Close();
                GetStKartBrmSet();
            }
            catch (Exception Ex)
            {
                try
                {
                    //StKartBrmSetTransaction.Rollback();
                }
                catch
                {
                    //
                }
                Response.Redirect("../Public/ErrInf.aspx?ErrMsgId=101&ErrMsgDsc=" + Ex.Message.ToString());
            }
        }
6.Resim resize
using System.Drawing;

using System.Drawing.Imaging;


public class CreateThumbNail : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
      {
            string Image = Request.QueryString["Image"];
            if (Image == null) 
            {
                  this.ErrorResult();
                  return;
            }

            string sSize = Request["Size"];

            int Size = 120;

            if (sSize != null)

                  Size = Int32.Parse(sSize);

            string Path = Server.MapPath(Request.ApplicationPath) + "" + Image;

            Bitmap bmp = CreateThumbnail(Path,Size,Size);

            if (bmp == null)

            {

                  this.ErrorResult();

                  return;

            }

            string OutputFilename = null;

            OutputFilename = Request.QueryString["OutputFilename"];

            if (OutputFilename != null)

            {
                  if (this.User.Identity.Name == "") 
                  {

                        // *** Custom error display here

                        bmp.Dispose();

                        this.ErrorResult();

                  }

                  try

                  {

                        bmp.Save(OutputFilename);

                  }

                  catch(Exception ex)
                  {

                        bmp.Dispose();

                        this.ErrorResult();

                        return;

                  }

            }

            // Put user code to initialize the page here

            Response.ContentType = "image/jpeg";

            bmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

            bmp.Dispose();

      }

      private void ErrorResult()

      {

            Response.Clear();

            Response.StatusCode = 404;

            Response.End();

      }

      ///

      /// Creates a resized bitmap from an existing image on disk.

      /// Call Dispose on the returned Bitmap object

      ///

      ///

      ///

      ///

      /// Bitmap or null

      public static Bitmap CreateThumbnail(string lcFilename,int lnWidth, int lnHeight)

      {
  

            System.Drawing.Bitmap bmpOut = null;

            try

            {

                  Bitmap loBMP = new Bitmap(lcFilename);

                  ImageFormat loFormat = loBMP.RawFormat;



                  decimal lnRatio;

                  int lnNewWidth = 0;

                  int lnNewHeight = 0;

                  //*** If the image is smaller than a thumbnail just return it

                  if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)

                        return loBMP;

                  if (loBMP.Width > loBMP.Height)

                  {

                        lnRatio = (decimal) lnWidth / loBMP.Width;

                        lnNewWidth = lnWidth;

                        decimal lnTemp = loBMP.Height * lnRatio;

                        lnNewHeight = (int)lnTemp;

                  }

                  else

                  {

                        lnRatio = (decimal) lnHeight / loBMP.Height;

                        lnNewHeight = lnHeight;

                        decimal lnTemp = loBMP.Width * lnRatio;

                        lnNewWidth = (int) lnTemp;

                  }

                 // System.Drawing.Image imgOut =

                  //      loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,

                  //                              null,IntPtr.Zero);

                 

                  // *** This code creates cleaner (though bigger) thumbnails and properly

                  // *** and handles GIF files better by generating a white background for

                  // *** transparent images (as opposed to black)

                  bmpOut = new Bitmap(lnNewWidth, lnNewHeight);

                  Graphics g = Graphics.FromImage(bmpOut);

                  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                  g.FillRectangle( Brushes.White,0,0,lnNewWidth,lnNewHeight);

                  g.DrawImage(loBMP,0,0,lnNewWidth,lnNewHeight);

                  loBMP.Dispose();

            }

            catch

            {

                  return null;

            }

                  return bmpOut;
      }
}

7.
ienumerator Getenumerator ile dizi elemanlarını dolaşmak.

private void button1_Click(object sender, EventArgs e)
        {
            string[] adresdeger = new string[] { "Isparta", "Gönen", "Koçtepe" };
            System.Collections.IEnumerator dizioku = adresdeger.GetEnumerator();
            while (dizioku.MoveNext())
            {
                listBox1.Items.Add(dizioku.Current);
            }
        }
8.Herhangi bir exe dosyasını çalıştırmak.

string dosya;
dosya = @"d:windowssystem32calc.exe";
System.Diagnostics.Process.Start(dosya);

bu kodu yazdığımızda dosya isimli değişkene vermiş olduğumuz yerdeki program çalıştırılır.
bunların sadece exe olması gerekmez birlikteaç'ı belirli olan dosyalarıda açar.

string dosya;
dosya = @"d:windowssystem32mstsc.exe";
System.Diagnostics.Process.Start(dosya);

eğer herhangi bir exe'yi parametreli olarak çalıştıracaksak;

string dosya;
dosya = @"d:windowssystem32taskkill.exe";
System.Diagnostics.Process.Start(dosya,"/im winamp.exe");

kodu denemek için lütfen winampı açın ve kodu çalıştırın.
bu şekildeki exe dosyalarının parametrelerini windows yardım dosyalarından exe dosyanın ismini yazarak öğrenebilirsiniz.

9.PostBack kontrolü
if (!this.IsPostBack)
        {
        }
10.Web Config sqlConnections
string conStr = WebConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;

11.Çalıştır Komutu
System.Diagnostics.Process.Start("buraya açilacak dosyayi yaziyoruz");

12.Klasor olusturma -Klasor silme -Klasor Kopyalama
Klasor Olusturma

Directory.CreateDirectory("C:Klasörismi");

Klasor Silme

Directory.Delete("C:Silinen klasor");

Klasor  Tasima

File.Move("C:asıldosya.xxx", "C:denemegidilecekdosya.xxx");

13.ThreadPool işlemi
using System;
using System.Threading;

namespace KanalHavuzu
{
    class Sinan3
    {
        static void Main()
        {
            const sbyte MAX_THREAD = 10;
            ThreadPoolBeni [] thrd = new ThreadPoolBeni[MAX_THREAD + 1];
            Console.WriteLine("Ana kanalın id si" + AppDomain.GetCurrentThreadId());
            for (int i = 0; i < MAX_THREAD; ++i)
            {
                thrd[i] = new ThreadPoolBeni();
                Console.WriteLine("Kuyruktaki thread "+i.ToString()+" "+ThreadPool.QueueUserWorkItem(new WaitCallback(thrd[i].ThreadBeniLutfen),(object) i));
            }
            Console.WriteLine("oldu");
            Console.ReadKey();
        }
    }
    class ThreadPoolBeni
    {
        public void ThreadBeniLutfen(object State)
        {
            string id = "n/a";
            if (State != null)
                id = State.ToString();
            object[] o=new object[3] {id,AppDomain.GetCurrentThreadId(),Thread.CurrentThread.IsThreadPoolThread};
            Console.WriteLine(System.String.Format("{0} Kanal havuzundan selam sinan bunun Thread Id si={1} IsThreadPool u (o ne diye sorcan biliyom)={2}" ,o));
            Thread.Sleep(2000);
        }

    }

/* Burda sinan isimli bi arkadaşa bunu anlatmak için yaptım
ThreadPool Sınıfı birden fazla kanalı kuyruğa ekliyor ve
onları çalıştırıyor*/

14.Çalışma zamanında nesne oluşturma
Type t = Type.GetType("Sınıf Adı");

object o = Activator.CreateInstance(t);

15.sayısal loto
// sayısal loto tahmini

            listBox1.Items.Clear();
            Random rnd = new Random();
            int min = int.Parse(textBox1.Text);
            int max = int.Parse(textBox2.Text);
            int adet = int.Parse(textBox3.Text);
            for (int i = 1; i <= adet; i++)
            {
                int a = rnd.Next(min, max);
                listBox1.Items.Add(i+" ------------>  "+a);
            }

16.WebServisi: DataSet ile veri listeleme ve güncelleme. Ancak güncelleme için bir client yazılması gerekir.
using System;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Data.Sql;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    //private SqlConnection conn = new SqlConnection("User ID=sa;Initial Catalog=WSLab;Data Source=(local)");

    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
   
    //private SqlConnection conn = new SqlConnection("User ID=sa;Initial Catalog=WSLab;Data Source=(local)");
    private SqlConnection conn = new SqlConnection("User ID=user; Password=pass;Initial Catalog=Northwind;Data Source=192.168.0.160");

    [WebMethod]
    public System.Data.DataSet GetCategories(int id)
    {
        string strSQL = "select * from Categories where CategoryID=" + id.ToString();
        SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);
        System.Data.DataSet ds = new System.Data.DataSet();
        da.Fill(ds, "Categories");
        conn.Close();

        return ds;
    }

    [WebMethod]
    public void UpdateCategories(System.Data.DataSet ds, int id)
    {
        string strSQL = "select * from Categories where CategoryID=" + id.ToString();
        SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);
        SqlCommandBuilder custCB = new SqlCommandBuilder(da);
        conn.Open();
        da.Update(ds, "Categories");
        conn.Close();
    }

}

*PictureBox Kontrolü
// resim yüklemek:**********************************************

string yol;
yol=@"D:Resimlergüneş.jpg";
pictureBox1.Image=Image.FromFile(yol);

// kontrol üzerindeki resmin harddiske kayıt edilmesi***********

string yol;
saveFileDialog1.Title="Resim Kaydet";
saveFileDialog1.DefaultExt="bmp";
if(saveFileDialog1.ShowDialog()==DialogResult.Ok)
{
yol=saveFileDialog1.FileName;
pictureBox1.Image.Save(yol);
}

17.Bindingsource işlemi
// kontrollerin  binding edilmesi (Veri tabanı bilgilerinin kontrollere bağlanması) *******************************************
// kodların çalışması için öncelikle veritabanına bağlantının yapılmış olması gerekir.( bkz. Access Veritabanına kodla bağlanmak)


textBox1.DataBindings.Add("Text", bindingSource1, "Sehir");
dateTimePicker1.DataBindings.Add("Text", bindingSource1, "tarih");


dataGridView1.DataSource = bindingSource1;


// Bir sütunun toplamını almak: **************************************************

public string alantopla(string alan)
        {
            double toplam = 0;
            foreach (DataRowView kayit in bindingSource1.List)
            {
                double deger = Convert.ToDouble(kayit[alan].ToString());
                toplam += deger;
               
            }
            string topla=toplam.ToString("#,###.00 YTL");
            return topla;
        }
// label1.text=alantopla("fiyat");

// Sütun bilgilerine erişmek : ****************************************
using System.Collections; // eklenecek

IList oku=bindingsource1.List;
foreach(DataRowView kayit in Oku)
{
listbox1.Items.Add(kayit["kitap"]);
}

// filtreleme işlemi .  *********************************************************

            string kriterim;
            kriter = textBox4.Text;
            bindingSource1.Filter ="isim='"+kriterim+"'";

//filtrelemeyi iptal etmek : bindindsource1.RemoveFilter();


// birden fazla parametre ile filtreleme yaptırmak:

string kitapkriter;
            double adetkriter;
            string sonuc;
            urunkriter = textBox7.Text;
            adetkriter = Convert.ToDouble(textBox8.Text);
            sonuc="kitap='"+urunkriter+"'AND adet>='"+adetkriter+"'";
            bindingSource1.Filter=sonuc;


// Kayıt Aramak  ***************************************************

string krit;
            krit = textBox5.Text;
            int num = bindingSource1.Find("kitap", krit);
            if (num >= 0)
            {
                bindingSource1.Position = num;
            }

// Kayıt Aramak 2 ****************************************************31.982

private void textBox6_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter)
            {
                string metinkriter;
                metinkriter=textBox6.Text;
                int numara=bindingSource1.Find("kitap",metinkriter);
                if(numara>=0)
                {
                    bindingSource1.Position=numara;
                    DataRowView satir=(DataRowView)bindingSource1.Current;
                    label6.Text=satir["kitap"].ToString();
                    double sonuc=Convert.ToDouble(satir["fiyat"].ToString());
                    label7.Text=sonuc.ToString("#,###.00 YTL");
                }
                else
                {
                    MessageBox.Show("Bulunamadı..");
                }
            }
        }

// Aktif Kayıt Hücre İçeriklerine Erişmek ************************************31.984

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataRowView aktifkayit;
            aktifkayit = (DataRowView)bindingSource1.Current;
            string kitapad = aktifkayit["kitap"].ToString();
            string fiyat = aktifkayit["fiyat"].ToString();
            MessageBox.Show("Seçilen kitap= " + kitapad + "nfiyat= " + fiyat);
        }
// Sıralama İşlemi :*******************************************************31.987

private void button12_Click(object sender, EventArgs e)
        {
            bindingSource1.Sort = "kitap DESC";
        }

        private void button13_Click(object sender, EventArgs e)
        {
            bindingSource1.Sort = "kitap ASC";
        }

        private void button14_Click(object sender, EventArgs e)
        {
            bindingSource1.Sort = "kitap ASC,adet ASC";
        }
// sıralamayı iptal etmek :  bindingsource1.RemoveSort();



// aktif kaydın nosu öğreniliyo*********************************************31.986
            int no = bindingSource1.Position + 1;
            string sonuc = no.ToString();
            label10.Text = sonuc;

// Aktif Kaydı Sil 1. yöntem :**********************************************31.987

DialogResult mesaj;
            mesaj = MessageBox.Show("Eminsin?", "kayıt sil", MessageBoxButtons.YesNo);
            if (mesaj == DialogResult.Yes)
            {
                bindingSource1.RemoveCurrent();
                MessageBox.Show("silindi..");
            }
// Aktif kaydı sil 2.yöntem:

int kayitno;
            kayitno = bindingSource1.Position;
            bindingSource1.RemoveAt(kayitno);

18.Datasetteki bir alanın elemanlarını listbox ta göstermek.
// using System.Collections;  eklenecek.

IList Oku = bindingSource1.List;
           foreach (DataRowView kayit in Oku)
           {
               listBox1.Items.Add(kayit["Baslik"]);
           }

19.Access Veri Tabanına Kodla Bağlanmak
// Not: Bu kodlar dataset üzerinde geçerlidir.
// Doğrudan Veritabanı tablosunu etkilemez..
// Projeye 1 Adet bindingsource dahil edin.


using System.Data.OleDb; // Bunu eklemeyi unutmayın..

namespace binding
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Provider ve Veritabanını belirten string tanımlanıyo:
            String BaglanStr = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=kitap.mdb";
            // Hangi tablodan hangi bilgiyi istediğimizi bildiren string tanımlanıyo:
            String Sorgu = "Select * From kitap1";
            // Veri tabanıyla bağlantı kuruluyo:
            OleDbConnection Baglanti = new OleDbConnection(BaglanStr);
            // Veri tabanının tablosuyla bağlantı kuruluyo:
            OleDbDataAdapter VeriAl = new OleDbDataAdapter(Sorgu, Baglanti);
            //Data tablosu tanımlanıyo:
            DataTable tablo = new DataTable();
            // "tablo" adındaki tabloya veritabanı tablosundaki veriler alınıyo:
            VeriAl.Fill(tablo);
            //DataSet tanımlanıyo :
            DataSet Al = new DataSet();
            //DataSet içine "tablo" aktarılıyo:
            Al.Tables.Add(tablo);
            // bindingsource1 ile DataSet ilişkilendiriliyo:
            bindingSource1.DataSource = Al;
            // bindingsource1' e ilgili tablo bağlanıyo:
            bindingSource1.DataMember = Al.Tables[0].TableName;

            // Not: Bu kodlar dataset üzerinde geçerlidir.
            // Doğrudan Veritabanı tablosunu etkilemez..

20.Kayıt İşlemleri
private void button1_Click(object sender, EventArgs e)
        {
            //İlk kayda git
            bindingSource1.MoveFirst();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //Son kayda git
            bindingSource1.MoveLast();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //Önceki kayda git
            int no = bindingSource1.Position;
            if (no <= 0)
            {
                MessageBox.Show("Zaten ilk kayıttasınız..!");
            }
            else
            {
                bindingSource1.MovePrevious();
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //Sonraki kayda git
            int kayitno, kayitsayisi;
            kayitno = bindingSource1.Position;
            kayitsayisi = bindingSource1.Count;
            if (kayitno >= kayitsayisi - 1)
            {
                MessageBox.Show("Zaten son kayıttasınız");
            }
            else
            {
                bindingSource1.MoveNext();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Kayıt ekle
            bindingSource1.AddNew();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            // Aktif kaydı sil
            int kayitno;
            kayitno = bindingSource1.Position;
            bindingSource1.RemoveAt(kayitno);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            // DataSetteki değişiklikleri DataSete kaydet (VeriTabanına değil)
            bindingSource1.EndEdit();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            // Değişiklikleri iptal et
            bindingSource1.CancelEdit();
        }

21.Temel İşlemler

// ikinci formu açmak **************************************************************
private void button5_Click(object sender, EventArgs e)
        {
            Form2 Frm2 = new Form2();
            Frm2.Show();
        }

//formu kapatmadan diğer formların kullanılması istenmiyosa ************************

Form2.Show.Dialod();

// Exe çalıştırmak: ****************************************************************

string dosya;
dosya="c:windowsnotepad.exe";        // veya dosya=@"c:windowsnotepad.exe";
System.Diagnostics.Process.Start(dosya);

// Bilgisayar ve Kullanıcı adını öğrenmek: *****************************************

this.text=System.Security.Principal.WindowsIdentity.GetCurrent().Name;

// uygulamayı ikinci formdan başlatmak: ********************************************

/* program.cs dosyasını aç ve "....(new Form1());" kısmını "....(new Form2());" yap

// sayısal içeriklere parasal format vermek:****************************************

decimal deger;
deger=255567;
string sonuc;
sonuc=deger.ToString("#,###.00 YTL");

// Zaman Gecikmesi oluşturmak: ******************************************(31.223)

using uyu=System.Threading.Thread; //using bölümüne eklenecek
uyku.Sleep(1000); // bir saniye bekle.

22.E-posta gönderimi
using System.Web.Mail;

public class MailSender {
public static void SendMail() {
   MailMessage message = new MailMessage();
   message.From = "kimden@domain.com";
   message.To = "kime@domain.com";
   message.Subject = "Konu";
   message.Body = "<b>Mesaj<b>";
   message.Format = MailFormat.Html;
   SmtpMail.SmtpServer = "mail.domain.com";
   SmtpMail.Send(message);
}
}
23.Tek Instance Uygulama
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace DotNetTurk
{
    internal class SingleInstanceManager
    {
        private static Mutex mutex;
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr FindWindow(string ClassName, string WindowText);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr ShowWindow(IntPtr hanlde, int mode);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetForegroundWindow(IntPtr hanlde);
        internal static bool Check()
        {
            mutex = new Mutex(true, "Uygulamam");
            if (!mutex.WaitOne(0, false))
            {
                IntPtr handle = FindWindow(null, "Ana Form Başlığı");
                ShowWindow(handle, 1);
                SetForegroundWindow(handle);
                return false;
            }
            return true;
        }
    }
}

// Kullanımı
        static void Main(string[] args)
        {
            if (!SingleInstanceManager.Check())
                return;
            ...
        }

24.Sunucudaki ODBC DSN lerin listesini almak
//Amaç:
//ODBC DSN lerinin listesini getirmek

//Çalışma şekli
CHelpers cHelpers = new CHelpers ();
string[] lsServer; //DSN adları
string[] lsDriver; //DSN Driver ları
iRet = cHelpers.GetDataSources (out lsServer, out lsDriver,3);
if (iRet < 0)
    return iRet;
if (lsServer == null)
    return -1;


//Ana kütüphane CHelpers.cs
//Kodu doğrudan WebService 'in altındaki bir
//kütüphane üzerinde çalışması için hazırlamıştım.
//Dolayısı ile doğrudan kullanımda
//gereksiz yerlerin çıkartılması gerekir.
//Bu örnekte return Array üzerine basılıyor,
//gerektiğinde XML formatınada basılması
//biraz değişiklikle mümkün olacaktır.
//Adnan Boz

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]

namespace FOBFDomain
{
    public class Win32 
    {
        [DllImport("odbc32.dll", EntryPoint = "SQLDataSources")]
        public static extern Int16 SQLDataSources(
            Int32 hEnv,
            Int16 fDirection,
            [MarshalAs (UnmanagedType .VBByRefStr )]ref string szDSN,
            Int16 cbDSNMax,
            ref Int16 pcbDSN,
            [MarshalAs (UnmanagedType .VBByRefStr )]ref string szDescription,
            Int16 cbDescriptionMax,
            ref Int16 pcbDescription);

        [DllImport("odbc32.dll", EntryPoint = "SQLAllocHandle")]
            //[return : MarshalAs(UnmanagedType.I4)]
        public static extern Int16 SQLAllocHandle(
            Int16 HandleType,
            Int16 InputHandle,
            ref Int32 OutputHandlePtr);


        [DllImport("odbc32.dll", EntryPoint = "SQLSetEnvAttr")]
        public static extern Int16 SQLSetEnvAttr(
            Int32 EnvironmentHandle,
            Int16 dwAttribute,
            Int16 ValuePtr,
            Int16 StringLen);

        [DllImport("odbc32.dll")]
        public static extern Int16 SQLFreeHandle(
            Int16 HandleType,
            Int32 Handle);

    }
    /// <summary>
    /// Summary description for CHelpers.
    /// </summary>
    public class CHelpers
    {
        private const Int16 SQL_MAX_DSN_LENGTH = 32;
        private const Int16 SQL_MAX_DESC_LENGTH = 128;
        private const Int16 SQL_SUCCESS = 0;
        private const Int16 SQL_FETCH_NEXT = 1;
        private const Int16 SQL_FETCH_FIRST = 1;
        private const Int16 SQL_FETCH_FIRST_USER = 31;
        private const Int16 SQL_FETCH_FIRST_SYSTEM = 32;
        private const Int16 SQL_NULL_HANDLE = 0;
        private const Int16 SQL_HANDLE_ENV = 1;
        private const Int16 SQL_ATTR_ODBC_VERSION = 200;
        private const Int16 SQL_OV_ODBC3 = 3;
        private const Int16 SQL_IS_INTEGER = (-6);


        public CHelpers()
        {

        }

        /// <summary>
        /// dsnType =
        ///  1 = User
        ///  2 = System
        ///  3 = User + System
        /// </summary>
   
        public int GetDataSources(out string[] sServer /*DSN adları array 'i*/,
            out string[] sDriver /*DSN lerin Driver array 'i */,
            int dsnType)
        {
           
            Int32 hEnv = 0;        //handle to the environment
            int retCode = 0;
            string[] lsServer = new string [100];
            string[] lsDriver = new string [100];
            string slServer = "";
            string slDriver = "";
            Int16 nSvrLen = 0;
            Int16 nDvrLen = 0;
               

            long sqlRet = Win32.SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE, ref hEnv);
  
            //obtain a handle to the environment
            if (sqlRet == 0 || sqlRet == 1)
            {

                //if successful, set the
                //environment for subsequent calls
                sqlRet = Win32.SQLSetEnvAttr(hEnv,SQL_ATTR_ODBC_VERSION, SQL_OV_ODBC3, SQL_IS_INTEGER);
                if (sqlRet == 0 || sqlRet == 1)
                {


                    //set up the strings for the call
                    slServer = slServer.PadLeft ((int)SQL_MAX_DSN_LENGTH,' ');
                    slDriver = slDriver.PadRight((int)SQL_MAX_DESC_LENGTH, ' ');

                    int i = 0;
                    //load the DSN names
                    Int16 toFetch = 0;
                    switch (dsnType)
                    {
                        case 1:
                            toFetch = SQL_FETCH_FIRST_USER;
                            break;
                        case 2:
                            toFetch = SQL_FETCH_FIRST_SYSTEM;
                            break;
                        case 3:
                            toFetch = SQL_FETCH_FIRST;
                            break;
                    }

                    sqlRet = Win32.SQLDataSources(hEnv,
                            toFetch,
                            ref slServer,
                            SQL_MAX_DSN_LENGTH,
                            ref nSvrLen,
                            ref slDriver,
                            SQL_MAX_DESC_LENGTH,
                            ref nDvrLen);

                    while (sqlRet == SQL_SUCCESS)
                    {

                        lsServer[i] = slServer;
                        lsDriver[i] = slDriver;
                        i ++;
                        //repad the strings
                        slServer = slServer.PadLeft ((int)SQL_MAX_DSN_LENGTH,' ');
                        slDriver = slDriver.PadRight((int)SQL_MAX_DESC_LENGTH, ' ');

                        sqlRet = Win32.SQLDataSources(hEnv,
                            SQL_FETCH_NEXT,
                            ref slServer,
                            SQL_MAX_DSN_LENGTH,
                            ref nSvrLen,
                            ref slDriver,
                            SQL_MAX_DESC_LENGTH,
                            ref nDvrLen);

                    }
                    if (i>0)
                    {
                        sServer = new string[i];
                        sDriver = new string[i];
                        for (int k=0;k < i;k++)
                        {
                            sServer[k] = ClearString(lsServer[k]);
                            sDriver[k] = ClearString(lsDriver[k]);
                        }
                    }
                    else
                    {
                        retCode = -1;
                        goto error;
                    }
                }
                else
                {
                    retCode = -2;
                    goto error;
                }
               


                //clean up
                Win32.SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

            }
            else
            {
                retCode = -3;
                goto error;
            }

           

            return 0;

            error:
                if (retCode > -3)
                    Win32.SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

                sServer = null;
                sDriver = null;
                return retCode;

        }

        private string ClearString(string s2Clear)
        {
            return s2Clear.Replace ("","");
        }
    }
}


25.ASP.NET Text Image
/* Örnek Kullanımı:
* TextImage1.LocalPath = "c:InetpubwwwrootTestAppTemp"; (Temp yazılabilir olmalıdır)
* TextImage1.RemotePath = "http://localhost/TestApp/Temp/";
* TextImage1.FileName = "Test.jpg";
* TextImage1.Text = "Deneme Başlık";
* TextImage1.CreateImage();
*/
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI.Design;
using System.Drawing;
using System.Drawing.Imaging;

namespace DotNetTurk.Web.UI.WebControls
{

    [DefaultProperty("Text"),
        ToolboxData("<{0}:TextImage runat=server></{0}:TextImage>")]
    public class TextImage : System.Web.UI.WebControls.WebControl
    {

        public TextImage()
        {
            Width = 10;
            Height = 10;
        }
        [Bindable(true),
            Category("Appearance"),
            DefaultValue("")]        
        public string Text
        {
            get
            {
                return text;
            }

            set
            {
                text = value;
            }
        }
        public string FileName
        {
            get
            {
                object o = ViewState["FileName"];
                return (o == null) ? String.Empty : (string)o;
            }
            set
            {
                ViewState["FileName"] = value;
            }
        }
       
        public string RemotePath
        {
            get
            {
                object o = ViewState["RemotePath"];
                return (o == null) ? String.Empty : (string)o;
            }
            set
            {
                ViewState["RemotePath"] = value;
            }
        }

        public string LocalPath
        {
            get
            {
                object o = ViewState["LocalPath"];
                return (o == null) ? String.Empty : (string)o;
            }
            set
            {
                ViewState["LocalPath"] = value;
            }
        }

        private System.Drawing.Font GetFont()
        {
            System.Drawing.Font f = new System.Drawing.Font(this.Font.Name, float.Parse(this.Font.Size.Unit.Value.ToString()));
            return f;
        }

        public void CreateImage()
        {
            Bitmap bitmap = new Bitmap(int.Parse(Width.Value.ToString()), int.Parse(Height.Value.ToString()));
            Graphics g = Graphics.FromImage(bitmap);
            g.Clear(BackColor);
            g.DrawString(Text, GetFont(), new SolidBrush(ForeColor), 2, 2);
            bitmap.Save(LocalPath + FileName, ImageFormat.Jpeg);           
        }

        protected override void Render(HtmlTextWriter output)
        {
            string FullPath = RemotePath + FileName;
            output.Write("<img src="" + FullPath + "" width=" + Width.ToString() + " height=" + Height.ToString() + ">");
        }
    }
}

26.C# Thread
using System;
Gereken Componentler:
Form1

progressBar1
progressBar2

buttonBaslat
buttonDuraklat
buttonDevam
buttonDurdur

Ne işe yarar:
Aynı anda iki metodu çalıştırmamız gerekebilir. Böyle durumlarda Thread'ları kullanabiliriz.


Kodlar:

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

namespace Thread_1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        public void z1()
        {

            for (int i = 1; i < 100; ++i)
            {
                progressBar1.Value += 1;

                Thread.Sleep(30);//Bu metodu kullanan thread 30 ms bekleyecek, sonra işlemine devam edecek.                   
            }
        }

        public void z2()
        {
            for (int k = 1; k < 100; ++k)
            {
                progressBar2.Value += 1;
                Thread.Sleep(50);//Bu metodu kullanan thread 50 ms bekleyecek, sonra işlemine devam edecek.
            }
        }

        Thread T1 = null; //Threadları tanımlıyoruz.
        Thread T2 = null;       

        private void buttonBaslat_Click(object sender, EventArgs e)
        {
            ThreadStart TS1 = new ThreadStart(z1); //Metodları threadlarla ilişkilendirmek için ThreadStart sınıfından bir nesene oluşturulup ilişkilendirmek istediğimiz metod parametre olarak veriliyor.
            ThreadStart TS2 = new ThreadStart(z2);

            T1 = new Thread(TS1); //T1 Threadına TS1 ThreadStart nesnesi ile metodumuz ilişkilendiriliyor.
            T2 = new Thread(TS2);

            T1.Start(); //T1 Threadı çalışmaya başladı.
            T2.Start();

            buttonBaslat.Enabled = false;
        }

        private void buttonDuraklat_Click(object sender, EventArgs e)
        {
            T1.Suspend(); //T1 threadı duraklatıldı.
            T2.Suspend();
        }

        private void buttonDevam_Click(object sender, EventArgs e)
        {
            T1.Resume(); //Daha önceden duraklatılmış olan T1 threadı kaldığı yerden devam ettiriliyor.
            T2.Resume();
        }

        private void buttonDurdur_Click(object sender, EventArgs e)
        {
            T1.Abort(); //T1 Threadı kapatılıyor. Resume metodu ile yeniden başlatılamaz artık.
            T2.Abort();

            progressBar1.Value = 0;
            progressBar2.Value = 0;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (T1.IsAlive || T2.IsAlive) //Thread halen kapatılmadıysa ilgili threadın IsAlive özelliği true değeri döndürü, kapalı ise false;
            {
                MessageBox.Show("Halen açık olan iş parçacıkları kapatılacak");
                if (T1.IsAlive) T1.Abort();
                if (T2.IsAlive) T2.Abort();
            }
        }

27.İşletim sistemi sürümünün alınması
OperatingSystem os = Environment.OSVersion;
MessageBox.Show(os.Version.ToString());
MessageBox.Show(os.Platform.ToString());

28.WebBrowser da yazdırırken başlığın ayarlanması
public void SetupHeaderWB()
{
  string strPath = "SoftwareMicrosoftInternet ExplorerPageSetup";
  Microsoft.Win32.RegistryKey oKey = null;

  /* The following lines of code takes care that error does not occur if registry settings are not at proper path.*/
  oKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey (strPath, true);
  if (oKey! =null)
   {
    oKey = microsoft.Win32.Registry.CurrentUser.OpenSubKey (strPath, true);
   }
  else
   {
    oKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (strPath, true);
   }
   
   string strKey = "header";
   object oValue = "Test Başlık";   
   oKey.SetValue (strKey, oValue);
   /* You can also get the value in registry by following line of code
      string strValue=oKey.GetValue (strKey).ToString();*/
   oKey.Close();
}

29.Web.Config okunması
// önce referans vermek gerekiyor System.Configuration'a

string deger = ConfigurationManager.AppSettings["deneme"];

30.Ana formun gizli olarak yaratılması
using System;
using System.Collections.Generic;
using System.Windows.Forms;

    public class Program
    {
        private static ApplicationContext context;
        [STAThread]

        static void Main(string[] args)
        {
            context = new ApplicationContext();

            Application.Idle += new EventHandler(OnAppIdle);

            Application.Run(context);
        }

        private static void OnAppIdle(object sender, EventArgs e)
        {
            if (context.MainForm == null)
            {
                Application.Idle -= new EventHandler(OnAppIdle);

                context.MainForm = new ManinForm();

            }
        }
    }

31.O anki assembly lokasyonunun alınması
System.Reflection.Assembly.GetExecutingAssembly().Location

32.Başlığı olmayan ve boyutu değiştirilebilir form yaratmak
        private void Form1_Load(object sender, EventArgs e)
        {
            Text = string.Empty;
            ControlBox = false;
        }

33.Sistem hakkında çeşitli bilgiler alma

Bilgisayar adı,SystemInformation.ComputerName
Domain adı,SystemInformation.UserDomainName
Boot modu,SystemInformation.BootMode.ToString()
Ağ,SystemInformation.Network.ToString()
Güvenlik,SystemInformation.Secure.ToString()
Menü font,SystemInformation.MenuFont.ToString()
Monitör sayısı,SystemInformation.MonitorCount.ToString()
Fare durumu,SystemInformation.MousePresent.ToString()
Fare buton sayısı,SystemInformation.MouseButtons.ToString()
Fare butonlarının değiştirildiği bilgisi,SystemInformation.MouseButtonsSwapped.ToString()
Farede whell durumu,SystemInformation.MouseWheelPresent.ToString()
Sesler,SystemInformation.ShowSounds.ToString()           
Kullanıcı adı,SystemInformation.UserName
34.Windows uygulamasından mail göndermek
using System.Diagnostics;

Process process = new Process();
process.StartInfo.FileName = "mailto:email@address1.com,email@address2.com?subject=konu&cc=email@address3.com
&bcc=email@address4.com&body=mesaj" ;
process.Start();

35.Sistemdeki fontların alınması
comboBox1.Items.AddRange(FontFamily.Families);

36.Ses Dosyası Çalma
 
Belirtilen yoldaki müzik dosyasını oynatan program kodu (.net Framework 2.0 gereklidir)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Media// Eklenmesi gereken namespace.
 
namespace WindowsApplication1
{
    public 
partial class Form1 Form
    
{
        public 
Form1()
        {
            
InitializeComponent();
        }
 
        private 
void Form1_Load(object senderEventArgs e)
        {
            
SoundPlayer player = new SoundPlayer();
            
string path "C:windowsmediading.wav"// Müzik adresi
            
player.SoundLocation path;
            
player.Play(); //play it
        
}
    }
 
37.Klasik Duvar saati
using System;
using System.Windows.Forms;
using System.Drawing;

class MyForm : Form
{
MyForm ()
{
Text = "Clock";
SetStyle (ControlStyles.ResizeRedraw, true);
}

protected override void OnPaint (PaintEventArgs e)
{
SolidBrush red = new SolidBrush (Color.Red);
SolidBrush white = new SolidBrush (Color.White);
SolidBrush blue = new SolidBrush (Color.Blue);

// Initialize the transformation matrix
InitializeTransform (e.Graphics);

// Draw squares denoting hours on the clock face
for (int i=0; i<12; i++) {
e.Graphics.RotateTransform (30.0f);
e.Graphics.FillRectangle (white, 85, -5, 10, 10);
}

// Get the current time
DateTime now = DateTime.Now;
int minute = now.Minute;
int hour = now.Hour % 12;

// Reinitialize the transformation matrix
InitializeTransform (e.Graphics);

// Draw the hour hand
e.Graphics.RotateTransform ((hour * 30) + (minute / 2));
DrawHand (e.Graphics, blue, 40);

// Reinitialize the transformation matrix
InitializeTransform (e.Graphics);

// Draw the minute hand
e.Graphics.RotateTransform (minute * 6);
DrawHand (e.Graphics, red, 80);

// Dispose of the brushes
red.Dispose ();
white.Dispose ();
blue.Dispose ();
}

void DrawHand (Graphics g, Brush brush, int length)
{
// Draw a hand that points straight up, and let
// RotateTransform put it in the proper orientation
Point<> points = new Point<4>;
points<0>.X = 0;
points<0>.Y = -length;
points<1>.X = -12;
points<1>.Y = 0;
points<2>.X = 0;
points<2>.Y = 12;
points<3>.X = 12;
points<3>.Y = 0;

g.FillPolygon (brush, points);
}

void InitializeTransform (Graphics g)
{
// Apply transforms that move the origin to the center
// of the form and scale all output to fit the form's width
// or height
g.ResetTransform ();
g.TranslateTransform (ClientSize.Width / 2,
ClientSize.Height / 2);
float scale = System.Math.Min (ClientSize.Width,
ClientSize.Height) / 200.0f;
g.ScaleTransform (scale, scale);
}

static void Main ()
{
Application.Run (new MyForm ());
}
}
 

38.Mesaj yazımı

using System;
using System.Windows.Forms;

namespace win1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult sonuc;
            sonuc = MessageBox.Show("Çıkmak istediğinizden emin misiniz?", "Uyarı", MessageBoxButtons.OKCancel);

            if (sonuc == DialogResult.OK)
                Application.Exit();

        }

        private void button2_Click(object sender, EventArgs e)
        {

            MessageBox.Show("mesajın iceriği!", "Uyarı", MessageBoxButtons.OKCancel);

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
39.Web browserımız.

//Copright by Ramazan GÜMÜŞKAR and Zeki GÖRÜR
//Saat:14.44tarih 14/08/2008
//Güle güle kullanın misafirler,arkadaşlar.

using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
public class Form1
{
    private void Form1_Load(object sender, System.EventArgs e)
    {
        this.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedToolWindow;
        this.buttonBack = new System.Windows.Forms.Button();
        this.buttonForward = new System.Windows.Forms.Button();
        this.buttonStop = new System.Windows.Forms.Button();
        this.buttonHome = new System.Windows.Forms.Button();
        this.buttonRefresh = new System.Windows.Forms.Button();
        this.TextBox1 = new System.Windows.Forms.TextBox();
        this.buttonSubmit = new System.Windows.Forms.Button();
        this.WebBrowser1 = new System.Windows.Forms.WebBrowser();
        this.SuspendLayout();
        //
        //buttonBack
        //
        this.buttonBack.Location = new System.Drawing.Point(12, 12);
        this.buttonBack.Name = "buttonBack";
        this.buttonBack.Size = new System.Drawing.Size(75, 23);
        this.buttonBack.TabIndex = 0;
        this.buttonBack.Text = "Geri";
        this.buttonBack.UseVisualStyleBackColor = true;
        //
        //buttonForward
        //
        this.buttonForward.Location = new System.Drawing.Point(93, 12);
        this.buttonForward.Name = "buttonForward";
        this.buttonForward.Size = new System.Drawing.Size(75, 23);
        this.buttonForward.TabIndex = 1;
        this.buttonForward.Text = "İleri";
        this.buttonForward.UseVisualStyleBackColor = true;
        //
        //buttonStop
        //
        this.buttonStop.Location = new System.Drawing.Point(174, 12);
        this.buttonStop.Name = "buttonStop";
        this.buttonStop.Size = new System.Drawing.Size(75, 23);
        this.buttonStop.TabIndex = 2;
        this.buttonStop.Text = "Durdur";
        this.buttonStop.UseVisualStyleBackColor = true;
        //
        //buttonHome
        //
        this.buttonHome.Location = new System.Drawing.Point(255, 12);
        this.buttonHome.Name = "buttonHome";
        this.buttonHome.Size = new System.Drawing.Size(75, 23);
        this.buttonHome.TabIndex = 3;
        this.buttonHome.Text = "Giriş";
        this.buttonHome.UseVisualStyleBackColor = true;
        //
        //buttonRefresh
        //
        this.buttonRefresh.Location = new System.Drawing.Point(336, 12);
        this.buttonRefresh.Name = "buttonRefresh";
        this.buttonRefresh.Size = new System.Drawing.Size(75, 23);
        this.buttonRefresh.TabIndex = 4;
        this.buttonRefresh.Text = "Yenile";
        this.buttonRefresh.UseVisualStyleBackColor = true;
        //
        //TextBox1
        //
        this.TextBox1.Location = new System.Drawing.Point(12, 41);
        this.TextBox1.Name = "TextBox1";
        this.TextBox1.Size = new System.Drawing.Size(399, 20);
        this.TextBox1.TabIndex = 5;
        this.TextBox1.Text = "www.google.com.tr";
        //buttonSubmit
        //
        this.buttonSubmit.Location = new System.Drawing.Point(417, 12);
        this.buttonSubmit.Name = "buttonSubmit";
        this.buttonSubmit.Size = new System.Drawing.Size(75, 49);
        this.buttonSubmit.TabIndex = 6;
        this.buttonSubmit.Text = "&Git";
        this.buttonSubmit.UseVisualStyleBackColor = true;
        //
        //WebBrowser1
        //
        this.WebBrowser1.Location = new System.Drawing.Point(12, 67);
        this.WebBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
        this.WebBrowser1.Name = "WebBrowser1";
        this.WebBrowser1.Size = new System.Drawing.Size(655, 427);
        this.WebBrowser1.TabIndex = 7;
        //
        //Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(679, 506);
        this.Controls.Add(this.WebBrowser1);
        this.Controls.Add(this.buttonSubmit);
        this.Controls.Add(this.TextBox1);
        this.Controls.Add(this.buttonRefresh);
        this.Controls.Add(this.buttonHome);
        this.Controls.Add(this.buttonStop);
        this.Controls.Add(this.buttonForward);
        this.Controls.Add(this.buttonBack);
        this.Name = "Form1";
        this.Text = "YerliBrowser V.0.1";
        this.ResumeLayout(false);
        this.PerformLayout();
       
        buttonBack.Enabled = false;
        buttonForward.Enabled = false;
        buttonStop.Enabled = false;
    }
   
    private void buttonBack_Click(object sender, System.EventArgs e)
    {
        WebBrowser1.GoBack();
        TextBox1.Text = WebBrowser1.Url.ToString();
    }
   
    private void buttonForward_Click(object sender, System.EventArgs e)
    {
        WebBrowser1.GoForward();
        TextBox1.Text = WebBrowser1.Url.ToString();
    }
   
    private void buttonStop_Click(object sender, System.EventArgs e)
    {
        WebBrowser1.Stop();
    }
   
    private void buttonRefresh_Click(object sender, System.EventArgs e)
    {
        WebBrowser1.Refresh();
    }
   
    private void buttonHome_Click(object sender, System.EventArgs e)
    {
        WebBrowser1.GoHome();
        TextBox1.Text = WebBrowser1.Url.ToString();
    }
   
    private void buttonSubmit_Click(object sender, System.EventArgs e)
    {
        WebBrowser1.Navigate(TextBox1.Text);
    }
   
    private void WebBrowser1_CanGoBackChanged(object sender, System.EventArgs e)
    {
        if (WebBrowser1.CanGoBack == true) {
            buttonBack.Enabled = true;
        }
        else {
            buttonBack.Enabled = false;
        }
    }
   
    private void WebBrowser1_CanGoForwardChanged(object sender, System.EventArgs e)
    {
        if (WebBrowser1.CanGoForward == true) {
            buttonForward.Enabled = true;
        }
        else {
            buttonForward.Enabled = false;
        }
    }
   
    private void WebBrowser1_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
    {
        buttonStop.Enabled = false;
    }
   
    private void WebBrowser1_Navigated(object sender, System.Windows.Forms.WebBrowserNavigatedEventArgs e)
    {
        TextBox1.Text = WebBrowser1.Url.ToString();
        this.Text = WebBrowser1.DocumentTitle.ToString();
    }
   
    private void WebBrowser1_Navigating(object sender, System.Windows.Forms.WebBrowserNavigatingEventArgs e)
    {
        buttonStop.Enabled = true;
    }
    internal System.Windows.Forms.Button buttonBack;
    internal System.Windows.Forms.Button buttonForward;
    internal System.Windows.Forms.Button buttonStop;
    internal System.Windows.Forms.Button buttonHome;
    internal System.Windows.Forms.Button buttonRefresh;
    internal System.Windows.Forms.TextBox TextBox1;
    internal System.Windows.Forms.Button buttonSubmit;
    internal System.Windows.Forms.WebBrowser WebBrowser1;
}

40.
Şekli Değişik  Form  
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;

namespace NonSquareForm {
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form {
        private Point mouseOffset;
        private bool isMouseDown = false;

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1() {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
           
           
            // Read the background file
            //FileStream imageStream = File.OpenRead("Glass.bmp");
            //Bitmap imageBackground = (Bitmap)Bitmap.FromStream(imageStream);
            Bitmap imageBackground = new Bitmap(this.GetType(), "Glass.bmp");
            Color transparentColor = Color.FromArgb(0xFF, 0x00, 0xFF);

            // Make our form fit the background
            this.Width = imageBackground.Width;
            this.Height = imageBackground.Height;
           
            // Apply custom region with FF00FF as transparent color
            this.Region = RegionConvert.ConvertFromTransparentBitmap(imageBackground, transparentColor);
            // And set the background to our bitmap to finish everything
            this.BackgroundImage = imageBackground;       
        } /* Form1 */

        private void Form1_MouseDown(object sender,
            System.Windows.Forms.MouseEventArgs e) {
            int xOffset;
            int yOffset;

            if (e.Button == MouseButtons.Left) {
                xOffset = -e.X - SystemInformation.FrameBorderSize.Width;
                yOffset = -e.Y - SystemInformation.CaptionHeight -
                    SystemInformation.FrameBorderSize.Height;
                mouseOffset = new Point(xOffset, yOffset);
                isMouseDown = true;
            }   
        }
       
        private void Form1_MouseMove(object sender,
            System.Windows.Forms.MouseEventArgs e) {
            if (isMouseDown) {
                Point mousePos = Control.MousePosition;
                mousePos.Offset(mouseOffset.X, mouseOffset.Y);
                Location = mousePos;
            }
        }

        private void Form1_MouseUp(object sender,
            System.Windows.Forms.MouseEventArgs e) {
            // Changes the isMouseDown field so that the form does
            // not move unless the user is pressing the left mouse button.
            if (e.Button == MouseButtons.Left) {
                isMouseDown = false;
            }
        }
       
        private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) {
            if ((int)e.KeyCode == 'Q') {
                Application.Exit();
            }
        }
       
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing ) {
            if( disposing ) {
                if (components != null) {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(154, 129);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "Form1";
            this.Text = "Form1";
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
            this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
            this.Load += new System.EventHandler(this.Form1_Load);
            this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseUp);
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() {
            Application.Run(new Form1());
        }

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


using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace System.Drawing.Drawing2D {
    public class RegionConvert {
        public static Region ConvertFromTransparentBitmap(Bitmap imageRegion, Color transparentColor) {
            // First we get the dimensions of our image
            GraphicsUnit aPixel = GraphicsUnit.Pixel;
            RectangleF imageBoundsF = imageRegion.GetBounds(ref aPixel);
            int imageWidth = Convert.ToInt32(imageBoundsF.Width);
            int imageHeight = Convert.ToInt32(imageBoundsF.Height);

            // This will be the path for our Region
            GraphicsPath regionPath = new GraphicsPath();

            // We loop over every line in our image, and every pixel per line
            for (int intY = 0; intY < imageHeight; intY++) {
                for (int intX = 0; intX < imageWidth; intX++) {   
                    if (imageRegion.GetPixel(intX, intY) != transparentColor) {
                        // We have to see this pixel!
                        regionPath.AddRectangle(new Rectangle(intX, intY, 1, 1));
                    }
                }
            }
           
            Region formRegion = new Region(regionPath);
            regionPath.Dispose();
            return formRegion;
        } /* ConvertFromTransparentBitmap */
    } /* RegionConvert */
} /* System.Drawing.Drawing2D  */

42.

Mesajbox 21 Temmuz 2008 17:12
//önce bi olay oluşturcaksın. mesela butona tıklandıgında istedigin uyarı cıksın gibisinden..
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("mesajın iceriği!", "Uyarı", MessageBoxButtons.OKCancel);
}

//diğer butonlar:
//MessageBoxButtons.AbortRetryIgnore
//MessageBoxButtons.OK
//MessageBoxButtons.RetryCancel
//MessageBoxButtons.YesNo
//MessageBoxButtons.YesNoCancel

/*bu uyarı kutusundan dönen değeri de kullanacaksındır. sadece "OK" olsa illa bir değer beklemek gerekmez ama OK ve CANCEL oldugu için bir değer bekliyor ve o değere göre işlem yapacağız demektir.*/

/*mesela çıkış butonumuz olsun. butona tıklayınca, uyarı kutusu çıkacak. OK, CANCEL olarak..*/

/*ok e tıklayınca programdan çıkış sağlanacak, iptal e tıklayınca da cıkış gerçekleşmeyecek.. şöyle ki;*/

private void button1_Click(object sender, EventArgs e)
{
DialogResult sonuc;
sonuc = MessageBox.Show("Çıkmak istediğinizden emin misiniz?", "Uyarı", MessageBoxButtons.OKCancel);

if (sonuc == DialogResult.OK)
Application.Exit();
}

/*(çıkış işlemi için buradaki butonları evet hayır olarak belirtmek daha mantıklı olur herhalde..)

veya;*/

private void button1_Click(object sender, EventArgs e)
{
DialogResult sonuc;
sonuc = MessageBox.Show("Çıkmak istediğinizden emin misiniz?", "Uyarı", MessageBoxButtons.OKCancel);

if (sonuc == DialogResult.OK)
MessageBox.Show("Tamam a tıklandı!", "Sonuç");
else if (sonuc == DialogResult.Cancel)
MessageBox.Show("İptal e tıklandı!", "Sonuç");
}
privatevoid Form1_FormClosed(object sender, FormClosedEventArgs e)
{
DialogResult kapat;
kapat = MessageBox.Show("Çıkmak istedi§inizden emin misiniz?", "Uyarı..!", MessageBoxButtons.YesNo);
if (kapat == DialogResult.Yes)
MessageBox.Show("İyi Günlenler", "Güle Güle");
elseif (kapat == DialogResult.No)
ActiveForm.ShowDialog(); //bunu deneme yanılma ile buldum
//ActiveForm.ShowDialog Formu kapatmadan Geri Döner

}

43.


İnteger tipte girilen sayınin içinde kaç tane 100 ,50,10,5 ve 1 lik oldunu bulan progrm 30 Haziran 2008 19:56
ilk olarak forma 4 adet TExtBox ekleyin ...
textbaox1 in adını para olarak değiştirin..
2. text 100 ler
3. text 50 ler
4. text 10 lar
5. text 5 ler
6. text 1 ler
basamağıdır...
Arır adında bir class oluşturuyorum...
ve içinde :

public class ayır
{

int Para
{
get { return this.paramız; }
set { this.paramız = value; }
}

public void gelenPara(int GPara)
{
this.paramız = GPara;
ParaAyırYuzluk(this.paramız);
}
void ParaAyırYuzluk(int PARA)
{
sonuc[0] = PARA / 100;
ParaAyırEllilik(this.paramız - (sonuc[0]*100));
}
void ParaAyırEllilik(int PARA)
{
sonuc[1] = PARA / 50;
ParaAyırOnluk(this.paramız - (sonuc[0] * 100 + sonuc[1] * 50));
}

void ParaAyırOnluk(int PARA)
{
sonuc[2] = PARA / 10;
ParaAyırBeslik(this.paramız - (sonuc[0] * 100 + sonuc[1] * 50 + sonuc[2] * 10));
}
void ParaAyırBeslik(int PARA)
{
sonuc[3] = PARA / 5;
ParaAyırBirlik(this.paramız - (sonuc[0] * 100 + sonuc[1] * 50 + sonuc[2] * 10 + sonuc[3] *5));
}
void ParaAyırBirlik(int PARA)
{
sonuc[4] = PARA / 1;
}

public int[] sonuc = new int[5];
private int paramız;
}

tanımlıyorumm... VE ANA PROGRAMA GELDiğimizde ben button nesnesinle gerçekleştirdim ,sizde istediğiniz gibi yapabilirsiniz


private void button1_Click(object sender, EventArgs e)
{ int gpara;
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
try
{
gpara = int.Parse(para.Text);
ayır AYR = new ayır();
AYR.gelenPara(gpara);
textBox2.Text = AYR.sonuc[0].ToString();
textBox3.Text = AYR.sonuc[1].ToString();
textBox4.Text = AYR.sonuc[2].ToString();
textBox5.Text = AYR.sonuc[3].ToString();
textBox6.Text = AYR.sonuc[4].ToString();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}

kodları yazıyorum ve program t
amam dır..
43.
Bu web sitesi ücretsiz olarak Bedava-Sitem.com ile oluşturulmuştur. Siz de kendi web sitenizi kurmak ister misiniz?
Ücretsiz kaydol