Hi in this tutorial we are going to see how to populate the data from sql database to DataGrid. For this tutorial i used northwind database . You can download the database from this link. Create a New Project and and add datagridview to your form.
Then add the following Code to your Project:
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 test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
string query = "Select *from Employees";
SqlConnection constr = Constr();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", constr);
cmd.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Exception:" + ex.ToString());
}
}
/*Create Connection String*/
private SqlConnection Constr()
{
string sqlConnection = @"Data Source= DESKTOP-LR8BT4M\GAMER;Initial Catalog=Northwnd;Integrated Security=True";
SqlConnection constr = new SqlConnection(sqlConnection);
return constr;
}
}
}
No comments:
Post a Comment