This article is based on the original article that was previously written using an older version of Visual Studio. You can find the original article on the below link:
Step 1: Make a database with a table in SQL Server.
1
Figure 1
Step 2: Create a Windows Application and add DataGridView on the Form. Now add a DataGridView control to the form by selecting it from Toolbox and set properties according to your needs.
2
Figure 2
Adding Source Code for GridView
Now you can add these few lines of code anywhere you want to load the data from the database. It may be a mouse button click or the Form load event handler.
  1. private void Form1_Load(object sender, EventArgs e) {
  2. SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", "server = MCNDESKTOP33; database = Avinash; UID = sa; password = *******");
  3. DataSet ds = new DataSet();
  4. da.Fill(ds, "Student");
  5. dataGridView1.DataSource = ds.Tables["Student"].DefaultView;
  6. }
Step 3: Code for the Save and Reset button
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Data.SqlClient;
  11. namespace WindowsFormsDataGrid {
  12. public partial class Form1: Form {
  13. public Form1() {
  14. InitializeComponent();
  15. }
  16. private void Form1_Load(object sender, EventArgs e) {
  17. SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", "server = MCNDESKTOP33; database = Avinash; UID = sa; password = *******");
  18. DataSet ds = new DataSet();
  19. da.Fill(ds, "Student");
  20. dataGridView1.DataSource = ds.Tables["Student"].DefaultView;
  21. }
  22. private void button1_Click(object sender, EventArgs e) {
  23. SqlConnection con = new SqlConnection("server = MCNDESKTOP33; database = Avinash; UID = sa; password = *******");
  24. con.Open();
  25. string qur = "INSERT INTO Student VALUES ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
  26. SqlCommand cmd = new SqlCommand(qur, con);
  27. cmd.ExecuteNonQuery();
  28. con.Close();
  29. MessageBox.Show("Inserted sucessfully");
  30. textBox1.Text = "";
  31. textBox2.Text = "";
  32. textBox3.Text = "";
  33. textBox4.Text = "";
  34. }
  35. private void button2_Click(object sender, EventArgs e) {
  36. textBox1.Text = "";
  37. textBox2.Text = "";
  38. textBox3.Text = "";
  39. textBox4.Text = "";
  40. }
  41. }
  42. }
Output: The contents of DataGridView look as in the below figure.
Figure 3
3
How to Run
Add using System.Data.SqlClient; namespace in your project.
Change the database path in this string. "server = MCNDESKTOP33; database = Avinash; UID = sa; password = *******"
Run the application.
To read other articles based on the same DataGridView application functionality, please click on the below references link: