Home » Tech Corner, Windows Controls in Visual studio

Filling a DataGridView-Windows Controls

4 June 2009 No Comments Posted By:LG

DataGridView
                 Is the windows control equivalent to gridview web control.Both are visual studio controls.Here i am trying to explain how to bind values to a datagridview from a table.
Pre-Requisites
1.)  Open visual studio and start a  project, and add a windows form.
2.)  From toolbox there is a tab”DATA”  from this add a DATAGRIDVIEW control.
3.)  A table is made in a certain structure(MS-SqlServer is used here,Table structure given below).
4.)  A class named “DBAccess.cs” is made for database connectivity(Explained below).Read More

                  After creating the page and placing a “DATAGRIDVIEW” in the page, first thing we must do to bind a table to the DataGridView control is to create a database connection.For making the sqlserver connection easier a user defined class “DBAccess.cs” is used in which all the database activities are done.The class is there at the bottom of the page,or you can Download it here.Hope it is understandable.
                    Now in the code section of the form,an object of this class is made.And using this object the methods inside the classes are used. A “GetTable( )” will help you execute a select query.This method returns a DataTable  “dt” which can is set as the DataSource of the DataGridView.

Form1.cs (The code behind file of the windows form)
       In the code below WindowsSample1 is the name of the project,Form1 is the name of the form. 

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;

namespace WindowsSample1
{

    public partial class Form1 : Form
    {
        DBAccess dba = new DBAccess();
        public Form1()
        {
            InitializeComponent();
        }
    private void Form1_Load(object sender, EventArgs e)
        {
            dba.GetTable(“select * from SampleTable”);
            dgv_SampleDataGridView.DataSource = dba.dt;
        }
    }
}

Table Structure

            There is no need to explain the table structure here but am doing it  because we are using the same table to do the edit,update and delete operations in a DataGridView So no confusion arises at that time.

TableName : SampleTable
Fields:

PKey                     varchar(50)       Primary key of the table
FieldName          varchar(50)      A column
AnotherField     varchar(50)      A column
RowStatus            int                        A column to indicate the status, by default it is 1.

DBAccess.cs

using System;
using System.Data;
using System.Configuration;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.Common;
 
public class DBAccess
{

    public SqlConnection sqlCon = new SqlConnection();
    public SqlCommand sqlCmd = new SqlCommand();
    public SqlDataAdapter sqlDa = new SqlDataAdapter();
    public DataTable dt;
    public DBAccess()
    {
      sqlCon.ConnectionString = “server=.;uid=sa;pwd=admin;database=test”;
    }

private SqlConnection GetConnection()
{
    try
    {
        if (sqlCon.State == ConnectionState.Open)
        { sqlCon.Close(); }
        sqlCon.Open();
    }
    catch (Exception ex)
    { sqlCon.Close(); }
    return sqlCon;
}

public DataTable GetTable(string sql)
{
    try
    {
     sqlCmd.Connection = GetConnection();
     sqlCmd.CommandType = CommandType.Text;
     sqlCmd.CommandText = sql;
     sqlDa.SelectCommand = sqlCmd;
     dt = new DataTable();
     sqlDa.Fill(dt);
     if (sqlCon.State == ConnectionState.Open)
     { sqlCon.Close(); }
    }
    catch (Exception ex)
    {
        if (sqlCon.State == ConnectionState.Open)
        { sqlCon.Close(); }
    }
    return dt;
}

public int ExecuteQuery(string sql)
  {
    int rslt = 0;
    try
    {
        sqlCmd.Connection = GetConnection();
        sqlCmd.CommandType = CommandType.Text;
        sqlCmd.CommandText = sql;
        rslt = sqlCmd.ExecuteNonQuery();
        if (sqlCon.State == ConnectionState.Open)
            { sqlCon.Close(); }
    }
    catch (Exception ex)
    {
        if (sqlCon.State == ConnectionState.Open)
        { sqlCon.Close(); }
    }
    return rslt;
  }
}

OutPut Screenshot

screenshot3tt.jpg

Related posts:

  1. TreeView Navigation Control in VisualStudio2008

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>