Display data from database to datagridview and update,delete data in datagridview using csharp

03/06/2017   12:52:11 PM

Hello,in this c# tutorial i will explain how to display data from sql server to the datagridview in csharp.then how to update and delete that data from datagridview.SqlCommandBuilder predefined class used here for display and modify data in to datagridview .  

What is SqlCommandBuilder ?

1.It is predefined class in ADO.NET

2.Automatically generates single table commands  update,delete,insert in a single database table for a DataAdapter  

3.This class cannot be inherited.

1 .Create a database name as Employee .Create a Table name as EmployeeDetails in this database.

Column Name

Data Types

EmpId

Int [Identity Property Set =True]

EmpName

varchar(50)

EmpDesgn

varchar(50)

 

2. Open VisualStudio.Net /  Select C# / Windows Application 

 

3. Make the design of the form as Follows.Add the following controls from toolbox on form

1.DataGridView

2.Two Buttons for update and select data

4.Add the following code for Display,Update,Delete data from dataGridView

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace UpdateandDelGridViewData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection cn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Employee;Integrated Security=True");
SqlDataAdapter da;
SqlCommandBuilder bldr;
DataTable dt;
 
private void btnDel_Click(object sender, EventArgs e)
{
try
{
dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
da.Update(dt);
MessageBox.Show("Record has been Deleted");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
 
private void btnUpdt_Click(object sender, EventArgs e)
{
try
{
da.Update(dt);
MessageBox.Show("Record has been Updated");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
Display();
}
private void Display()
{
da = new SqlDataAdapter("Select * From EmployeeDetails", cn);
bldr = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgv.DataSource = bs;
}
}
}

Output

                   

Support us by Sharing