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.
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.
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.
- private void Form1_Load(object sender, EventArgs e) {
- SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", "server = MCNDESKTOP33; database = Avinash; UID = sa; password = *******");
- DataSet ds = new DataSet();
- da.Fill(ds, "Student");
- dataGridView1.DataSource = ds.Tables["Student"].DefaultView;
- }
Step 3: Code for the Save and Reset button
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Data.SqlClient;
-
- namespace WindowsFormsDataGrid {
-
- public partial class Form1: Form {
-
- public Form1() {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e) {
- SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", "server = MCNDESKTOP33; database = Avinash; UID = sa; password = *******");
- DataSet ds = new DataSet();
- da.Fill(ds, "Student");
- dataGridView1.DataSource = ds.Tables["Student"].DefaultView;
- }
-
- private void button1_Click(object sender, EventArgs e) {
- SqlConnection con = new SqlConnection("server = MCNDESKTOP33; database = Avinash; UID = sa; password = *******");
- con.Open();
- string qur = "INSERT INTO Student VALUES ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
-
- SqlCommand cmd = new SqlCommand(qur, con);
- cmd.ExecuteNonQuery();
- con.Close();
- MessageBox.Show("Inserted sucessfully");
- textBox1.Text = "";
- textBox2.Text = "";
- textBox3.Text = "";
- textBox4.Text = "";
- }
-
- private void button2_Click(object sender, EventArgs e) {
- textBox1.Text = "";
- textBox2.Text = "";
- textBox3.Text = "";
- textBox4.Text = "";
-
- }
- }
- }
Output: The contents of
DataGridView look as in the below figure.
Figure 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: