Click here to Skip to main content
16,016,738 members
Articles / Programming Languages / C#

Using a DataGrid

Rate me:
Please Sign up or sign in to vote.
2.70/5 (30 votes)
22 Mar 2008CPOL 72.7K   1K   32   11
How to use a DataGrid control.

Using DataGrid

Introduction

This is a simple example to show you how to link and edit a data source through a DataGrid control.

What is a DataGrid

DataGrid is a data bound list control that displays the items from a data source in a table-like mode. The DataGrid control allows you to select, sort, add, delete, and edit these items.

How to Use a DataGrid

I think I have commented everything in the code; however, if I missed anything, please let me know.

C#
//By Muammar Yacoob

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//################# Required Library #################//
using System.Data.OleDb;
//####################################################//

namespace ez_Datagrid
{
    public partial class DG_Form : Form
    {
        //################# Needed Database Objects #################//
        OleDbConnection ConnectMe;
        DataSet ds;
        OleDbDataAdapter dap;
        //###########################################################//
        public DG_Form()
        {
            InitializeComponent();
        }

        private void btn_Connect_Click(object sender, EventArgs e)
        {
            //---------------- Connecting the database (mdb file) ------------------//

            //################## Creating the connection ###########################//
            ConnectMe = new OleDbConnection("Provider=Microsoft.Jet.OLEDB" + 
                        ".4.0;Data Source=" + txt_db_Location.Text);
            //######################################################################//
            try
            {
                //##### Connecting to the mdb file #####//
                ConnectMe.Open();
                //######################################//

                //###### Setting up buttons, text boxes and status bar ######//
                btn_Connect.Enabled = false;
                txt_db_Location.Enabled = false;
                btn_Fill.Enabled = true;
                txt_SQL.Enabled = true;
                status_Connection.Text = "Connected";
                //###########################################################//
            }
            catch (OleDbException)
            {
                MessageBox.Show("Cannot connect to " + txt_db_Location.Text);
             }

        private void btn_Fill_Click(object sender, EventArgs e)
        {
            //----------------------- Filling the datagrid -------------------------//
            try
            {
                //### Creating the sql command using the tables in the mdb file ###//
                OleDbCommand cmd = new OleDbCommand(txt_SQL.Text, ConnectMe);
                //#################################################################//

                //#### Creating the adabter according to the sql command ####//
                dap = new OleDbDataAdapter(cmd);
                //###########################################################//

                //#### Creating the dataset ####//
                ds = new DataSet();
                //##############################//

                //##### Filling the dataset #####//
                dap.Fill(ds);
                //###############################//

                //################ Filling the datagrid control ##################//
                //################ with the first & only table  ##############//
                //################ retrieved by the connection  ##################//
                dataGrid1.DataSource = ds.Tables[0];
                //################################################################//

                //########## I dont have to explain that again, do I?? ###########//
                btn_Fill.Text = "Refresh";
                btn_Update.Enabled = true;
                //################################################################//
            }
            catch (OleDbException)
            {
                MessageBox.Show("Please make sure you type in a correct SQL statement");
            }
        }

        private void btn_Update_Click(object sender, EventArgs e)
        {
            //-------------------------- Updating data ----------------------------//

            //############### Testing changes made to the dataset #################//
            if (ds.GetChanges() != null)
            //#####################################################################//
            {
            //########## generates a command that is used to #########//
            //########### merge changes made to the dataset ##########//
                OleDbCommandBuilder builder = new  OleDbCommandBuilder(dap);
            //########################################################//

                try
                {
                    //########### Getting changes made to the dataset ##########// 
                    //############# applay them against the adapter ############//
                    MessageBox.Show(dap.Update(ds.GetChanges()) + 
                                    " row(s) updated");
                    //##########################################################//

                    //######### Confirming changes made to the dataset ##########//
                    //############ and resetting it for new changes #############//
                    ds.AcceptChanges();
                    //###########################################################//
                }
                catch (InvalidOperationException)
                {
                    MessageBox.Show("Error retrieving data");
                    //######### Rejecting changes made to the dataset ########//
                    //############# through the datagrid control #############//
                    ds.RejectChanges();
                    //########################################################//
                }
            }
            else
            {
                MessageBox.Show("nothing to update", "Ez Datagrid", 
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

Points of Interest

Notice that you will get an error message if you try to connect to a table that doesn't contain a primary key.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Retired QSoft
Yemen Yemen
Biography?! I'm not dead yet!
www.QSoftOnline.com

Comments and Discussions

 
QuestionHow to calculate the salary column? Pin
danielwinata17-Apr-07 0:36
professionaldanielwinata17-Apr-07 0:36 
AnswerRe: How to calculate the salary column? Pin
Muammar©7-Feb-09 18:53
Muammar©7-Feb-09 18:53 
Hey Daniel,
I'm sorry but I just saw your post today..
You can always add total columns/rows by editing the select statement before filling the DataTable object..

Normally you have
SELECT ID, NAME, GRADE, SALARY


To add a total row you would add another select statement to the one above and combine them together to have something like
SELECT ID, NAME, GRADE, SALARY
FROM EMPS
UNION
SELECT COUNT(ID), '','',SUM(SALARY)
FROM EMPS
-- And the following line to make sure the total row stays at the bottom
ORDER BY SALARY


For a total column "although it's not logical to have one here" but suppose you have SALARY1 and SALARY2 as columns, then you can use something like
SELECT ID, NAME, GRADE, SALARY1, SALARY2, SALARY1 + SALARY2 AS "SALARY TOTAL"
FROM EMPS


And for your TextBox you would say
OleDbDataAdapter a = new OleDbDataAdapter(@"SELECT SUM(SALARY) AS ""SALARY TOTAL"" FROM TEST", ConnectMe);
DataTable dt = new DataTable("MyTotalsTable");
a.Fill(dt);
txtTotalSalary.Text = Convert.ToString(dt.Rows[0]["SALARY TOTAL"]);


I hope that answers your question and I'm sorry for the late replay.

Cheers,
Muammar.


All generalizations are wrong, including this one!
(\ /)
(O.o)
(><)

General//Nice comments Pin
Cold Blooded Coder5-Dec-06 23:52
Cold Blooded Coder5-Dec-06 23:52 
GeneralCool Pin
__SomeOne__5-Dec-06 23:24
__SomeOne__5-Dec-06 23:24 
GeneralRe Cool Pin
Fuse125-Dec-06 23:31
Fuse125-Dec-06 23:31 
GeneralRe: Cool Pin
Muammar©10-Dec-06 21:53
Muammar©10-Dec-06 21:53 
GeneralRe: Cool Pin
jlo14317-Feb-07 22:34
jlo14317-Feb-07 22:34 
NewsDownload source code link fixed Pin
Muammar©4-Sep-06 19:53
Muammar©4-Sep-06 19:53 
GeneralRe: Download source code link fixed Pin
ali1dc12-Sep-06 18:05
ali1dc12-Sep-06 18:05 
Generalwhy what's wrong?? Pin
Muammar©12-Sep-06 20:02
Muammar©12-Sep-06 20:02 
GeneralRe: why what's wrong?? Pin
Virendrak10-May-07 1:10
Virendrak10-May-07 1:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.