Ana Sayfa / Blog Yazılarım / c# Windows Form (Masaüstü) Ekstra özellikler

c# Windows Form (Masaüstü) Ekstra özellikler

  • BugraSoft
  • 26/12/2023
  • 2 Yorum
  • 137 Görüntülenme

Evet arkadaşlar bugün windows formda olan özellikleri inceleyeceğiz.


  • Giriş yapma özelliği


string kullanici = textBox1.Text;

string parola = textBox2.Text;

SqlCommand cmd = new SqlCommand();

conn.Open();

cmd.Connection = conn;

cmd.CommandText = "Select * from tblAdmin where kullaniciAdi='" + textBox1.Text + "'And parola='" + textBox2.Text + "'";

SqlDataReader dr;

dr = cmd.ExecuteReader();

if (dr.Read())

{

giris a = new giris();

a.Show();

this.Hide();

}

else

{ 

MessageBox.Show("Hatalı giriş");

}

conn.Close();



  • Textbox'a harf girilmesini engelleme kodu (KeyPress Olayı)


if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 44)

{

e.Handled = true;

}



  • Tarihe saat ekleme olayı


dtBas.Format = DateTimePickerFormat.Custom;

dtBas.CustomFormat = "dd/MM/yyyy HH:mm:ss";



  • DatagriedView'deki verileri textbox'a aktarmak (CellClick Olayı)


txtAciklama.Text = dgvGider.CurrentRow.Cells["Açıklama"].Value.ToString();

 txtSektör.Text = dgvGider.CurrentRow.Cells["Sektör Adı"].Value.ToString();

 txtFiyat.Text = dgvGider.CurrentRow.Cells["Tutar"].Value.ToString();

 object a = dgvGider.CurrentRow.Cells["Tarih"].Value;

 if (a != null && DateTime.TryParse(a.ToString(), out DateTime tarih))

 {

     // DateTimePicker'a tarihi aktar

     txtTarih.Value = tarih;

 }



  • DatagriedView'deki verileri PDF'e aktarmak


public static void PDF_Disa_Aktar(DataGridView dataGridView1)

 {

     SaveFileDialog save = new SaveFileDialog();

     save.OverwritePrompt = false;

     save.Title = "PDF Dosyaları";

     save.DefaultExt = "pdf";

     save.Filter = "PDF Dosyaları (*.pdf)|*.pdf|Tüm Dosyalar(*.*)|*.*";

     if (save.ShowDialog() == DialogResult.OK)

     {

         PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);

 

         // Bu alanlarla oynarak tasarımı iyileştirebilirsiniz.

         pdfTable.DefaultCell.Padding = 3; // hücre duvarı ve veri arasında mesafe

         pdfTable.WidthPercentage = 80; // hücre genişliği

         pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; // yazı hizalaması

         pdfTable.DefaultCell.BorderWidth = 1; // kenarlık kalınlığı

         // Bu alanlarla oynarak tasarımı iyileştirebilirsiniz.

 

         foreach (DataGridViewColumn column in dataGridView1.Columns)

         {

             PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));

             cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240); // hücre arka plan rengi

             pdfTable.AddCell(cell);

         }

         try

         {

             foreach (DataGridViewRow row in dataGridView1.Rows)

             {

                 foreach (DataGridViewCell cell in row.Cells)

                 {

                     pdfTable.AddCell(cell.Value.ToString());

                 }

             }

         }

         catch (NullReferenceException)

         {

         }

         using (FileStream stream = new FileStream(save.FileName + ".pdf", FileMode.Create))

         {

             Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);// sayfa boyutu.

             PdfWriter.GetInstance(pdfDoc, stream);

             pdfDoc.Open();

             pdfDoc.Add(pdfTable);

             pdfDoc.Close();

             stream.Close();

         }

     }

 }

PDF_Disa_Aktar(dgvGider);


  • DatagriedView'deki verileri Yazdırmak

İlk önce PrintDocument'in PrintPage olayına şunları yazıyoruz 

  

try

  {

      int iLeftMargin = e.MarginBounds.Left;

      int iTopMargin = e.MarginBounds.Top;

      bool bMorePagesToPrint = false;

      int iTmpWidth = 0;

      bFirstPage = true;

 

      if (bFirstPage)

      {

          foreach (DataGridViewColumn GridCol in dgvGelir.Columns)

          {

              iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /

                             (double)iTotalWidth * (double)iTotalWidth *

                             ((double)e.MarginBounds.Width / (double)iTotalWidth))));

 

              iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,

                          GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

 

 

              arrColumnLefts.Add(iLeftMargin);

              arrColumnWidths.Add(iTmpWidth);

              iLeftMargin += iTmpWidth;

          }

      }

 

      while (iRow <= dgvGelir.Rows.Count - 1)

      {

          DataGridViewRow GridRow = dgvGelir.Rows[iRow];

 

          iCellHeight = GridRow.Height + 5;

          int iCount = 0;

 

          if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)

          {

              bNewPage = true;

              bFirstPage = false;

              bMorePagesToPrint = true;

              break;

          }

          else

          {

              if (bNewPage)

              {

                  e.Graphics.DrawString("Gelirler"new Font(dgvGelir.Font, FontStyle.Bold),

                          Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -

                          e.Graphics.MeasureString("Gelirler"new Font(dgvGelir.Font,

                          FontStyle.Bold), e.MarginBounds.Width).Height - 13);

 

                  String strDate = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();

 

                  e.Graphics.DrawString(strDate, new Font(dgvGelir.Font, FontStyle.Bold),

                          Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -

                          e.Graphics.MeasureString(strDate, new Font(dgvGelir.Font,

                          FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -

                          e.Graphics.MeasureString("Gelirler"new Font(new Font(dgvGelir.Font,

                          FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                  iTopMargin = e.MarginBounds.Top;

                  foreach (DataGridViewColumn GridCol in dgvGelir.Columns)

                  {

                      e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),

                          new Rectangle((int)arrColumnLefts[iCount], iTopMargin,

                          (int)arrColumnWidths[iCount], iHeaderHeight));

 

                      e.Graphics.DrawRectangle(Pens.Black,

                          new Rectangle((int)arrColumnLefts[iCount], iTopMargin,

                          (int)arrColumnWidths[iCount], iHeaderHeight));

 

                      e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,

                          new SolidBrush(GridCol.InheritedStyle.ForeColor),

                          new RectangleF((int)arrColumnLefts[iCount], iTopMargin,

                          (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);

                      iCount++;

                  }

                  bNewPage = false;

                  iTopMargin += iHeaderHeight;

              }

              iCount = 0;

              foreach (DataGridViewCell Cel in GridRow.Cells)

              {

                  if (Cel.Value != null)

                  {

                      e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,

                                  new SolidBrush(Cel.InheritedStyle.ForeColor),

                                  new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,

                                  (int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);

                  }

                  e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],

                          iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));

 

                  iCount++;

              }

          }

          iRow++;

          iTopMargin += iCellHeight;

      }

      if (bMorePagesToPrint)

          e.HasMorePages = true;

      else

          e.HasMorePages = false;

  }

  catch (Exception exc)

  {

      MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

  }


Daha sonra ise printdocumentin beginprint olayına geliyoruz ve şunları yazıyoruz.


try

{

    strFormat = new StringFormat();

    strFormat.Alignment = StringAlignment.Near;

    strFormat.LineAlignment = StringAlignment.Center;

    strFormat.Trimming = StringTrimming.EllipsisCharacter;

 

    arrColumnLefts.Clear();

    arrColumnWidths.Clear();

    iCellHeight = 0;

    iRow = 0;

    bFirstPage = true;

    bNewPage = true;

 

    iTotalWidth = 0;

    foreach (DataGridViewColumn dgvGridCol in dgvGelir.Columns)

    {

        iTotalWidth += dgvGridCol.Width;

    }

}

catch (Exception ex)

{

    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}


Daha sonra ise bir butona ise şu kodları yazıyoruz.


PrintPreviewDialog onizleme = new PrintPreviewDialog();

onizleme.Document = printDocument1;

onizleme.ShowDialog();


  • DatagriedView içi boş mu kontrolü

if (dgvAidat.CurrentRow == null)

 {

     MessageBox.Show("Lüfen ödemek istediğiniz aidatı seçiniz", "Hatalı İşlem", MessageBoxButtons.OK, MessageBoxIcon.Error);

 }

  • Son ID numarasını bir arttırma kodu


conn.Open();

string sql9 = "select IDENT_CURRENT('tblMakbuz') +1";

SqlCommand cmd9 = new SqlCommand(sql9, conn);

SqlDataReader dr2 = cmd9.ExecuteReader();

if (dr2.Read())

{

   string o = dr2[0].ToString();

}

 

conn.Close();


  • Tarihi gün ay yıl olarak kaydetme


string sql2 = "set dateformat dmy Insert into tblMakbuz (daireNo, ad, soyad, aidatAdi, tutar, makTarih, ay, yıl) values (@daireNo, @ad, @soyad, @aidatAdi, @tutar, @makTarih, @ay , @yıl) select SCOPE_IDENTITY()";


  • Makbuz oluşturma verileri diğer forma taşıma


//tblmakbuzun son id'sini 1 arttırma

conn.Open();

string sql9 = "select IDENT_CURRENT('tblMakbuz') +1";

SqlCommand cmd9 = new SqlCommand(sql9, conn);

SqlDataReader dr2 = cmd9.ExecuteReader();

if (dr2.Read())

{

    o = dr2[0].ToString();

}

conn.Close();

 

//Aidat'ın bitti'sini 1 yapıp makbuz oluşturuyoruz

conn.Open();

string sql = "Update tblAidat set bitti=1 where ID='" + dgvAidat.CurrentRow.Cells[0].Value.ToString() + "' and daireNo= '" + dgvAidat.CurrentRow.Cells[4].Value.ToString() + "'";

SqlCommand cmd = new SqlCommand(sql, conn);

cmd.ExecuteNonQuery();

string sql2 = "set dateformat dmy Insert into tblMakbuz (daireNo, ad, soyad, aidatAdi, tutar, makTarih, ay, yıl) values (@daireNo, @ad, @soyad, @aidatAdi, @tutar, @makTarih, @ay , @yıl) select SCOPE_IDENTITY()";

SqlCommand cmd2 = new SqlCommand(sql2, conn);

cmd2.Parameters.AddWithValue("@daireNo", txtDaireNo.Text);

cmd2.Parameters.AddWithValue("@ad", lblAd.Text);

cmd2.Parameters.AddWithValue("@soyad", lblSoyad.Text);

cmd2.Parameters.AddWithValue("@aidatAdi", dgvAidat.CurrentRow.Cells[1].Value.ToString());

cmd2.Parameters.AddWithValue("@tutar", dgvAidat.CurrentRow.Cells[3].Value.ToString());

cmd2.Parameters.AddWithValue("@makTarih", DateTime.Now.ToString("d"));

cmd2.Parameters.AddWithValue("@ay", DateTime.Now.ToString("MMMM"));

cmd2.Parameters.AddWithValue("@yıl", DateTime.Now.ToString("yyyy"));

cmd2.ExecuteNonQuery();

//sağdaki griedview'de makbuzları gösteriyoruz

dgvMakbuz.DataSource = b.veriAl("Select * from VwMakbuz Where [Daire No]='" + txtDaireNo.Text + "'");

//aidat miktarını sakin borcundan düşüyoruz

string sql3 = "Update tblSakinler set borc = borc - " + dgvAidat.CurrentRow.Cells[3].Value.ToString() + " Where No = '" + txtDaireNo.Text + "'";

SqlCommand cmd3 = new SqlCommand(sql3, conn);

cmd3.ExecuteNonQuery();

conn.Close();

 

//yeni form açılıyor bilgileri buradan çekiyoruz.

aidatmakbuz a = new aidatmakbuz();

a.lblAidatAdi.Text = dgvAidat.CurrentRow.Cells[1].Value.ToString();

a.lblAd.Text = lblAd.Text + " " + lblSoyad.Text;

a.lblBorc.Text = lblBorc.Text;

a.lblTutar.Text = dgvAidat.CurrentRow.Cells[3].Value.ToString();

a.lblToplam.Text = dgvAidat.CurrentRow.Cells[3].Value.ToString();

a.lblDaireNo.Text = txtDaireNo.Text;

a.lblMakNo.Text = o;

a.lblBorc.Text = (Convert.ToInt32(lblBorc.Text) - Convert.ToInt32(dgvAidat.CurrentRow.Cells[3].Value.ToString())).ToString();

a.ShowDialog();

a.Dispose();

lblBorc.Text = (Convert.ToInt32(lblBorc.Text) - Convert.ToInt32(dgvAidat.CurrentRow.Cells[3].Value.ToString())).ToString();

dgvAidat.DataSource = b.veriAl("Select * from VwAidat Where [Daire No]='" + txtDaireNo.Text + "' and Bitti=0");

conn.Close();


  • DatagriedView'i Excel'e aktarma
İlk Önce Fonksiyonu oluşturup daha sonra butona en alttaki kodu yazacağız.

private void ExportToExcel(DataGridView dataGridView, string fileName)

 {

     using (XLWorkbook workbook = new XLWorkbook())

     {

         var worksheet = workbook.Worksheets.Add("Veri Sayfası");

 

         // İlk satır için başlık ve sistem tarihi

         var titleCell = worksheet.Range("A1:D1");

         titleCell.Merge().Value = "Uzay 2 Apartmanı Borçlular " + DateTime.Now.ToString("dd.MM.yyyy"); ;

         titleCell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

         titleCell.Style.Font.FontSize = 14;

         titleCell.Style.Font.Bold = true;

 

 

         // DataGridView'dan DataTable'a veri kopyalama

         DataTable dt = new DataTable();

         foreach (DataGridViewColumn column in dataGridView.Columns)

         {

             dt.Columns.Add(column.HeaderText);

         }

 

         foreach (DataGridViewRow row in dataGridView.Rows)

         {

             DataRow dataRow = dt.NewRow();

 

             for (int i = 0; i < dataGridView.Columns.Count; i++)

             {

                 dataRow[i] = row.Cells[i].Value;

             }

 

             dt.Rows.Add(dataRow);

         }

 

         // DataTable'dan verileri Excel sayfasına yazma

         worksheet.Cell(3, 1).InsertTable(dt);

 

         // Tüm hücrelerin ortalama hizalanması ve yazı boyutunun ayarlanması

         var cells = worksheet.CellsUsed();

         cells.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

         cells.Style.Font.FontSize = 14;

 

         // Sütun genişlikleri

         worksheet.Column(1).Width = 9; // 9 pixel

         worksheet.Column(2).Width = 36; // 36 pixel

         worksheet.Column(3).Width = 17.29; // 17.29 pixel

         worksheet.Column(4).Width = 15.71; // 15.71 pixel

 

         workbook.SaveAs(fileName);

     }

 

 }

  private void button3_Click_1(object sender, EventArgs e)

  {

      SaveFileDialog saveFileDialog = new SaveFileDialog();

      saveFileDialog.Filter = "Excel Files|*.xlsx;*.xls";

      saveFileDialog.Title = "Excel Dosyasını Kaydet";

      saveFileDialog.FileName = DateTime.Now.ToString("D") + " Tarihli Uzay 2 Borçlular Listesi.xlsx";

 

      if (saveFileDialog.ShowDialog() == DialogResult.OK)

      {

          ExportToExcel(dgvBorc, saveFileDialog.FileName);

      }

  }


  • DatagriedView'daki toplam sayıyı ekstra satıra kaydetme


//borçların toplamını son satıra yazdırma

 int satir3 = dgvBorc.Rows.Count - 1;

 int tutar3 = 0;

 for (int i = 0; i < satir3; i++)

 {

     tutar3 = tutar3 + Convert.ToInt32(dgvBorc.Rows[i].Cells["Borç"].Value.ToString()); 

 }

 dgvBorc.Rows[satir3].Cells["Borç"].Value = tutar3;

 dgvBorc.Rows[satir3].Cells["Durum"].Value = "Toplam Tutar";


  • Combobox seçimi engelleme (Disabled yapma)


txtAy.DropDownStyle = ComboBoxStyle.DropDownList;

txtAy.KeyPress += (sender, e) => { e.Handled = true; };


  • Combobox SQL'den veri çekme


string query2 = "SELECT ID, AY FROM tblAylar";

SqlDataAdapter adapter2 = new SqlDataAdapter(query2, conn);

DataTable table2 = new DataTable();

 

adapter2.Fill(table2);

 

txtAy.DisplayMember = "AY"; // ComboBox'ta gösterilecek sütun adı

txtAy.ValueMember = "AY"; // ComboBox'ta seçilen öğenin değerini belirleyen sütun adı

 

txtAy.DataSource = table2;

txtAy.SelectedIndex = 0; // İlk veriyi seçili getir


 

  • 2 Datetimepicker arasındaki tarih aralığını DataGriedView'e aktarma


DateTime bas = dtBas.Value.Date;  // Sadece tarih kısmını al

DateTime son = dtSon.Value.Date.AddDays(1).AddTicks(-1);  // Günün sonu (23:59:59) olarak ayarla


conn.Open();

DataTable dt = new DataTable();

string sql = "SELECT GiderId, [Açıklama], [Sektör Adı], Tutar, Tarih, [Ödeme Şekli], Ay, Yil FROM ViewGiderler WHERE Tarih BETWEEN @dtBas AND @dtSon";

SqlDataAdapter da = new SqlDataAdapter(sql, conn);

da.SelectCommand.Parameters.AddWithValue("dtBas", bas);

da.SelectCommand.Parameters.AddWithValue("dtSon", son);

da.Fill(dt);

dgvGider.DataSource = dt;

conn.Close(


 
  • DataGriedView sütun gizleme ve boyutlandırma


dgvGider.Columns["Ay"].Visible = false;

dgvGider.Columns["Yil"].Visible = false;

dgvGider.Columns["GiderId"].Visible = false;

dgvGider.Columns["Tarih"].Width = 60;

dgvGider.Columns["Tutar"].Width = 60;

dgvGider.Columns["Açıklama"].Width = 160;




Yorumlar

Mustafa Topal

Hocam mükemmel bilgiler

BugraSoft

Teşekkürler hocam

Yahya Cemal

<3

BugraSoft

<3 Hocammm

Yorum Yap