C# form ile veritabanı bağlantısı nasıl kurulur?

Toolbox’dan eklenecekler: 3 Label, 3 Button, 3 Textbox, 1 DataGridView.

Referansa Eklenecek:

using System.Data.SqlClient;

Form1 public partial class’ın altına yazılacak:

SqlConnection baglanti = new SqlConnection("Data Source=.;Initial Catalog=okul; Integrated Security=True");

void listele()
{
    if (baglanti.State==ConnectionState.Closed)
    {
        baglanti.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = baglanti;
        cmd.CommandText = "SELECT * FROM ogrenci";
        SqlDataAdapter adaptor = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adaptor.Fill(ds, "ogrenci");
        dataGridView1.DataSource = ds.Tables["ogrenci"];
        dataGridView1.Columns[0].Visible = false;
        baglanti.Close();
    }
}

void temizle()
{
    textBox1.Clear();
    textBox2.Clear();
    textBox3.Clear();
}

Form1_Load:

listele();

Button1_Click:

if (baglanti.State==ConnectionState.Closed)
{
    baglanti.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = baglanti;
cmd.CommandText = "INSERT INTO ogrenci(numara, ad, soyad) VALUES('" + int.Parse(textBox1.Text) + "', '" + textBox2.Text + "', '" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
baglanti.Close();
temizle();
listele();
MessageBox.Show("Kaydedildi!");

Button2_Click:

if (baglanti.State==ConnectionState.Closed)
{
    baglanti.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = baglanti;
cmd.CommandText = "UPDATE ogrenci SET numara='" + int.Parse(textBox1.Text) + "', ad='" + textBox2.Text + "', soyad='" + textBox3.Text + "' WHERE sirano='" + dataGridView1.CurrentRow.Cells[0].Value + "'";
cmd.ExecuteNonQuery();
cmd.Dispose();
baglanti.Close();
temizle();
listele();
MessageBox.Show("Güncellendi!");

DataGridView1_CellClick:

textBox1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();

textBox2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();

textBox3.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();

Button3_Click:

if (baglanti.State==ConnectionState.Closed)
{
    baglanti.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = baglanti;
cmd.CommandText = "DELETE FROM ogrenci WHERE sirano='" + dataGridView1.CurrentRow.Cells[0].Value + "'";
cmd.ExecuteNonQuery();
cmd.Dispose();
baglanti.Close();
temizle();
listele();
MessageBox.Show("Silindi!");

Çıktısı:

Bu alana reklam verebilirsiniz!