csharp

How to insert data into database in Windows Form using C#

In this blog, we will learn how to insert data into the database and bind DatagridView control in windows form using c#.

First, open windows form application drop three textboxes, three labels and one button. Change the button name open properties change the button name like “Submit”. Double click on the button for create button_click event. Let’s Start

Step 1. Open Sql Server create database and use this database.
[php]
create database InsertdataDemo
use InsertDataDemo
[/php]
Step 2.Create table
[php]
Create table StudentDetail(
StudentId int primary key identity(1,1),
Name varchar(30),
Age int,
Address varchar(20)
)
[/php]
Step 3. Create stored procedure for insert data.
[php]
create proc sp_studentDetail_insert
@name varchar(30),
@age int,
@address varchar(20)
as
begin
insert into StudentDetail(Name,Age,Address) values(@name,@age.@address)
end
[/php]

Step 4.Open App.config file for establishing a connection with a database.
[php]
<connectionStrings>
<add name="DBCS" connectionString="data source=.; initial catalog=InsertDataDemo;integrated security=true"/>
</connectionStrings>
[/php]

Open a Form1.cs page and write this code on the Form1.cs page.

[php]
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;
using System.Data.SqlClient;
using System.Configuration;

namespace InsertDataDemo
{
public partial class Form1: Form
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
public Form1()
{
InitializeComponent();
}

//Bind here datagridview control
public void BindGrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from StudentDetail", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
dataGrid.DataSource = ds.Tables[0];

}

}

//insert code write here for button click
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_studentDetail_insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@name",textBox1.Text);
cmd.Parameters.AddWithValue("@age", textBox2.Text);
cmd.Parameters.AddWithValue("@address", textBox3.Text);
int x= cmd.ExecuteNonQuery();
con.Close();
if (x > 0)
{
label4.Text = "Insert data successfully";
BindGrid();
}
else {
label4.Text = "Errorr ";
}

}

private void Form1_Load(object sender, EventArgs e)
{
//call BindGrid() method on Form1_Load Event
BindGrid();
}
}
}

[/php]

Demo

Any Suggestion and Question Related to this Article Please Comment. Thank You

Leave a Reply

Your email address will not be published.