Here are the steps:
Step 1: Go to Visual studio, select file, then New project as shown below:
Select
Windows Forms Application from the templates and change the application name, then set the location path and click OK button.
Step 2: After clicking OK button, Solution Explorer will appear in Visual Studio as
Step 3: Go to Form1.cs and design the form. I am designing for Student Details as in the following screenshot:
Step 4: Click on Insert button and after that we will redirect to Form1.cs, then write the following code:
- 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 Windows
- {
-
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void btnInsert_Click(object sender, EventArgs e)
- {
- SqlConnection con = new SqlConnection("Integrated security=true;Initial Catalog=tblStudent;Data source=.");
- SqlCommand cmd;
- con.Open();
- string s="insert into Student values(@p1,@p2,@p3)";
- cmd=new SqlCommand(s,con);
- cmd.Parameters.AddWithValue("@p1",txtSId.Text);
- cmd.Parameters.AddWithValue("@p2",txtSName.Text);
- cmd.Parameters.AddWithValue("@p3",txtSCourse.Text);
- cmd.CommandType = CommandType.Text;
- int i=cmd.ExecuteNonQuery();
- con.Close();
- MessageBox.Show(i+ " Row(s) Inserted ");
- }
- }
- }
Step 5: Run the application and check. You will get the following output screen:
Step 6: Enter the details and click on Insert button. You can see that a new message window is visible.
Message: 1 Row(s) has inserted.
Go to your database table and you can see New data which has been inserted is appearing in table data.
This is all about how to perform insert operation on the database through Windows application.