C# tutorial- DataGridView to display table from SQL Server database


Using DataGridView to display table from SQL Server database

In this post, you will learn to connect to SQL Server database and drop a table of the databae in the DataGridView control. The DataGridView has a property called DataSource that allows you to bind the table in to this control. You will use the BindingSource class to wrap the table and assign the data source from the BiningSource object to the DataGridView.



Now, let's create a class called DbServerhandler and define a method called readData to connect to and read the TblTest table from the SQL Server database called testdb. Here is the content of DbServerhandler class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
class DbServerhandler
{
private const string DbName = "testdb";
private const string TblName = "TblTest";
private static string conStr = "Server=ASPIREV5\\SQLEXPRESS; Database=" + DbName + ";User=dara;Password=dara;";
public static DataSet readData()
{
SqlConnection con = null;
SqlDataAdapter adapter = null;
DataSet ds=new DataSet();
try
{
con = new SqlConnection();
con.ConnectionString = conStr;
con.Open();
adapter = new SqlDataAdapter("Select * From " + TblName, con);

adapter.Fill(ds, TblName);

}
catch (Exception ex) { MessageBox.Show("Cannot read the database."); }

finally
{
if (con != null)
{
con.Close();

}
}

return ds;
}
}
}

You will need to drag and drop a DataGridView from the Toolbox on the left to the form. Then double-click the form to open the Form1_Load procedure and write the following code in it.

BindingSource bs = new BindingSource();
bs.DataSource = DbServerhandler.readData().Tables[0];
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bs;
dataGridView1.Refresh();

Now run the program. Here is the screenshot that shows the DataGridView displaying the data table from the database.

 

 

 




Comments

CAPTCHA image




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.