how to fill datagridview from database in c#
  • Hi, i have data in sql and i want to retrieve data from sql and want to fill in DataGridView in C#. what code should i use in C# because i dont want to use loops any other method for it please.
  • 4 Comments sorted by
  • Vote Up0Vote Down WaqasWaqas
    172.00 Karma Accepted Answer
    Hi add datagridview on your form and go to the column properties add column then set it name and then set it property name same as column name in database.
    below is form code.

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

    namespace WindowsFormsApplication3
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    SqlConnection con=new SqlConnection(@"Data Source=.\SqlExpress;Initial Catalog=DatabaseName;Integrated Security=True");
    DataTable dt = new DataTable();
    SqlDataAdapter sda = new SqlDataAdapter("select * from tblProduct", con);
    sda.Fill(dt);
    dataGridView1.DataSource = dt;
    }
    }
    }

    Grid1.JPG
    1024 x 768 - 129K
    Grid2.JPG
    1024 x 768 - 138K
  • Thanks. it's very helping. but there is a problem.
    what if someone want to load data using Entity framework.
  • Hey waqas why u use "sda"?
  • Hello @Haris 
    Here Waqas has created a new instance/object of SQL Data Adapter named sda. SQL Data Adapter is used to read data from DB using any query.
    You can read Details about SQL Data Adapter here https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(v=vs.110).aspx


Howdy, Stranger!

It looks like you're new here. If you want to get involved, or you want to Ask a new Question, Please Login or Create a new Account by Clicking below

Login with Facebook

Tagged

Popular Posts of the Week

Optimum Creative