Here in this article, I will show you how to connect a C# Application with Sql Server database.
Step 1: Open Sql Server, click on a New Database. Give the database name “dbSchool”.
Step 2: Now create a Table in database, You can name a table anything you want, here I named it “Student” . There are three columns in the table ID, FirstName and LastName like the following,
Form Design:
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; //For SQL Connection namespace sql_baglanti { public partial class Form1 : Form www.csharp-console-examples.com { public Form1() { InitializeComponent(); } SqlConnection con; SqlDataAdapter da; SqlCommand cmd; DataSet ds; void GetList() { con = new SqlConnection("server=.; Initial Catalog=dbSchool;Integrated Security=SSPI"); da = new SqlDataAdapter("Select *From Student", con); ds = new DataSet(); con.Open(); da.Fill(ds, "Student"); dataGridView1.DataSource = ds.Tables["Student"]; con.Close(); } private void Form1_Load(object sender, EventArgs e) { GetList(); } private void button1_Click(object sender, EventArgs e) // Insert Button { cmd = new SqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandText = "insert into Student(ID,FirstName,LastName) values (" + textBox1.Text + ",'" + textBox2.Text + "','" + textBox3.Text + "')"; cmd.ExecuteNonQuery(); con.Close(); GetList(); } private void button3_Click(object sender,EventArgs e)//Update Button { cmd =new SqlCommand(); con.Open(); cmd.Connection= con; cmd.CommandText="update Student set FirstName='"+ textBox2.Text+"',LastName='"+ textBox3.Text+"' where ID="+textBox1.Text+""; cmd.ExecuteNonQuery(); con.Close(); GetList(); } private void button4_Click(object sender,EventArgs e)//Delete Button { cmd =new SqlCommand(); con.Open(); cmd.Connection= con; cmd.CommandText="delete from Student where ID="+textBox1.Text+""; cmd.ExecuteNonQuery(); con.Close(); GetList(); } } |
Output: