This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

18 Sep 2013

Working with DataGridView in C#.Net and VB.Net windows forms application

# Bind Data to Datagridview in C#.Net, VB.NET Windows Application 
# Display/Fill/Populate Data in DataGridView in C#.Net, VB.NET Windows Application
# Bind data to DataGridView in Windows Forms in C#.Net and VB.Net

In this article i am going to explain about Binding Data to a DataGridView in C#.Net and VB.Net windows application . we can do this in two ways using SqlDataReader and SqlDataAdapter . Here we will see a small example of using SqlDataReader and SqlDataAdapter to bind data to DataGridView.
For this i am designing a form as follows.


The C# code in the code behind file is like this.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

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

        SqlCommand cmd;
        SqlDataReader reader;
        SqlConnection con = new SqlConnection("data source=localhost;initial catalog=mydb;Integrated security=true");
        // SqlConnection con = new SqlConnection("Data Source=<Server Name>;user id=<user name of sql server>;
                                       password=<password of sql server>;Initial Catalog=<Database Name>";


        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.ReadOnly = true;
        }

        /// <summary>
        ///  //function to bind data to datagridview using SqlDataReader
        /// </summary>
        public void BindGridUsingDataReader()
        {
            //for data table we have to include namespace System.Data
            DataTable table = new DataTable();
            cmd = new SqlCommand("SELECT * FROM EMPDetails", con);
            con.Open();
            reader = cmd.ExecuteReader();
            table.Load(reader);
            dataGridView1.DataSource = table;
            reader.Close();
            // table.Clear();
            con.Close();
            dataGridView1.ReadOnly = true;
        }

        /// <summary>
        /// //function to bind data to datagridview using SqlDataAdapter
        /// </summary>
        public void BindDataGridUsingDataAdapter()
        {
            DataSet ds = new DataSet();
            cmd = new SqlCommand("SELECT * FROM EMPDetails", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds); //filling DataSet
            dataGridView1.DataSource = ds.Tables[0];
        }

        /// <summary>
        /// button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_LoadGridDr_Click(object sender, EventArgs e)
        {
            try
            {
                BindGridUsingDataReader();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// button click code
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_LoadGridDa_Click(object sender, EventArgs e)
        {
            try
            {
                BindDataGridUsingDataAdapter();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}





The VB.Net Code in the Code behind file is

Imports System
Imports System.Data
Imports System.Data.SqlClient


Public Class Form1

    Public Sub New()
        InitializeComponent()
    End Sub

    Private cmd As SqlCommand
    Private reader As SqlDataReader
    Private con As New SqlConnection("data source=localhost;initial catalog=mydb;Integrated security=true")
    ' SqlConnection con = new SqlConnection("Data Source=<Server Name>;user id=<user name of sql server>;password=<password of sql server>;Initial Catalog=<Database Name>";


    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
        dataGridView1.AllowUserToAddRows = False
        dataGridView1.AllowUserToDeleteRows = False
        dataGridView1.[ReadOnly] = True
    End Sub

    ''' <summary>
    '''  //function to bind data to datagridview using SqlDataReader
    ''' </summary>
    Public Sub BindGridUsingDataReader()
        'for data table we have to include namespace System.Data
        Dim table As New DataTable()
        cmd = New SqlCommand("SELECT * FROM EMPDetails", con)
        con.Open()
        reader = cmd.ExecuteReader()
        table.Load(reader)
        dataGridView1.DataSource = table
        reader.Close()
        ' table.Clear();
        con.Close()
        dataGridView1.[ReadOnly] = True
    End Sub

    ''' <summary>
    ''' //function to bind data to datagridview using SqlDataAdapter
    ''' </summary>
    Public Sub BindDataGridUsingDataAdapter()
        Dim ds As New DataSet()
        cmd = New SqlCommand("SELECT * FROM EMPDetails", con)
        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds)
        'filling DataSet
        dataGridView1.DataSource = ds.Tables(0)
    End Sub
    ''' <summary>
    ''' button click to bindGrid using SqlDataReader
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btn_LoadGridDr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_LoadGridDr.Click
        Try
            BindGridUsingDataReader()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    ''' <summary>
    ''' button click to bindGrid using SqlDataAdapter
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btn_LoadGridDa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_LoadGridDa.Click
        Try
            BindDataGridUsingDataAdapter()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class


Output looks like this :



Download Source Code