How to insert data in windows application C#?

In this tutorial you will learn how to insert, update, and delete data using window application form C#. For fronted we used window form application and for backend we used SQL server for database.

Here you will learn step by step insert operation.

Step 1.

Create a New window form application C# in Microsoft Visual Studio.

new window

Step 2.

Now design your window form application like below form.

window form

Step 3.

Open your Microsoft SQL Server and create a table like as below. My default database is master.

create table

Step 4.

Now move to window form application(Form1.cs) and add following namespace in coding window. Simply double click on window form.

	
	using System.Data.SqlClient;
	
namespace

Step 5.

Now create a connection string to connect with Database. Make your Connection globally like below so that you can access it anywhere in the form.

The connection string that includes the source database name, and other parameters needed to establish the initial connection.

	
	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 Intsert
	{
    	public partial class Form1 : Form
    	{
        	public Form1()
        	{
            	InitializeComponent();
        	}

        	//globaly define conection
        	SqlConnection con = new SqlConnection("data source=DESKTOP-F3B3CCJ\SQLEXPRESS; database=master; uid=sa; password=123456;");
        	
    	}
	}
	

You will find your connection details in Sql Server. Open your Microsoft SQL Server.
Go to file menu → Connect Object Explorer….

connection

Step 6.

Now move to window form design view and double click on insert button. Add following code on your insert button click.

	
	private void button1_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into student values('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "')",con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Data Inserted Successfully.");
            con.Close();

        }
	

Now run you window form application. Press f5 key from keyword or from start button in Visual Studio.

Now enter the details and click on insert button.

insert message

Now move to Microsoft SQL Server and see your records in table. For that run SQL Server select query.

sql query
Next: how to update data in window application C#?
Advertisement here

Share this Page.