How to display data in DataGridView from sql server using csharp

08/03/2017   03:58:28 PM

Hello,in this c# tutorial i will explain how to select and display data from sql server database to DataGridView control in c#.DataGridView control used to display bulk data in tabular format.it is very useful control in c# to display data in table format.very few lines of code to select and display data to DataGridView

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

Column Name

DataTypes

EmpId

Int [Identity Property Set =True]

EmpName

varchar(50)

EmpDesgn

varchar(50)

EmpSalary

money

 

2. Open VisualStudio.Net / Select C# / Windows Application / Rename Form1.cs as EmployeeDetails.

3.Add DataGridView From VS.Net / View / Toolbox on Form1.design.cs

4.add the following code in to App.config file in </configuration> tag

<connectionStrings>
<add name="cn" connectionString="Data Source=.\sqlexpress;Initial Catalog=Employee;Integrated Security=True"/>
</connectionStrings>

 

5.Add a refrence System.Configurtation

Right click on refrences folder in project folder/Add Refernces / From Refrence Manager window/ Assemblies option / click on Framework option / select System.Configuration from list /click on ok

Now System.Configuration added in project

 

6.Create a class dbconnect.cs and add the following code in that class

using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
 
namespace ComboboxToTextboxdb
{
class dbConnect
{
public static string dbconnectivity()
{
return ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
}
}
}
 

 

7.Add the following code on Form1_Load event

 using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace DataGridviewdb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection cn = new SqlConnection(dbConnect.dbconnectivity());
SqlDataAdapter da;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select EmpId as EmployeeId, EmpName as Name ,EmpDesgn as EmployeeDesignation,EmpSalary as SalaryOfEmployee From EmployeeDetails", cn);
ds = new DataSet();
da.Fill(ds, "EmployeeDetails");
dgv.DataSource = ds;
dgv.DataMember = "EmployeeDetails";
}
}
}

Output

                   

Support us by Sharing