How to Bind Datatable to DataGridView Control in Windows Form Application
In this article, we will see How to Bind Datatable in DataGridView Control in Windows Form Application.If you want to show your data in a tabular form, then it is useful to you. Just follow the steps and you will be able to bind your own data table to the Data Grid View control.
Let's Starts:
1) Open Visual Studio and Go To => File => New => Select Windows Form Application.
2) There will be a blank windows form you can use drag and drop controls from the left side panel named "Toolbox", select DataGridview and drop it to your form.
3) Create a Database and add a table named 'details', data of that (details) table will be bind to this control, the schema of the table is as shown
4) write code for binding the data to DataGridView control as shown
Form1.cs Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
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 DGV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = LoadMyData();
dataGridView1.DataSource = dt;
}
internal DataTable LoadMyData()
{
DataTable dt = new DataTable();
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection connection = new SqlConnection(con);
string command = string.Format("Select * from Details");
SqlCommand sqlCommand = new SqlCommand(command, connection);
connection.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dt);
connection.Close();
return dt;
}
}
}
|
<add name="con" connectionString="Data Source=.;Initial Catalog=DotNetKida;Integrated Security=True" providerName="System.Data.SqlClient" />
4 Comments
Easy to follow thanks!!
ReplyDeleteThanks !! and feel free to ask any queries or to give any suggestions.
DeleteYo man! How D ?
ReplyDeleteUr blogs r appreciable, just outstanding. I like the way u write.
thank you for all this.
Just Keep going, i'll wait for more.
Yeah! I'm good..Thanks for your time and keep visiting for more !!...
Delete