Playing with DataGrid Control

转载 2004年07月19日 17:03:00

The article ?Playing with DATAGRID? presented above gives a user the overview to show the importance and versatility of the DATAGRID control.

Introduction <?XML:NAMESPACE PREFIX = O />


Accessing data has become a major programming task for modern software programming, both for standalone applications and for web-based applications. Microsoft's ADO.NET technology offers a solution to many of the problems associated with data access. Among the important part of ADO.NET ,DATAGRID control holds an important stature. Below is presented an article on DATAGRID and other related classes and how the user can play with them.

The versatile DataGrid control displays tabular data and supports selecting, sorting, and editing the data. Each data field is displayed in a separate column in the order it is stored in the database.

Adding Rows, columns and controls to the DataGrid dynamically


//include all the required namespaces

using System;



















public class TestDataGrid : System.Windows.Forms




/// Required designer variable.


private System.Windows.Forms.ComboBox cmbFunctionArea;
private DataTable                     dtblFunctionalArea;
private DataGrid                      dgdFunctionArea;


/// public constructor




public frmInitialShortListing()


      //automatically generated by the VS Designer

      //creates the object of the above designer variables



private void PopulateGrid()
      //Declare and initialize local variables used
DataColumn dtCol = null;//Data Column variable
string[]   arrstrFunctionalArea = null;//string array variable
System.Windows.Forms.ComboBox cmbFunctionArea;  //combo box var              
DataTable dtblFunctionalArea;//Data Table var


//Create the combo box object and set its properties
cmbFunctionArea               = new ComboBox();
cmbFunctionArea.Cursor        = System.Windows.Forms.Cursors.Arrow;
cmbFunctionArea.Dock          = DockStyle.Fill;
//Event that will be fired when selected index in the combo box is changed
      cmbFunctionArea.SelectionChangeCommitted += new   EventHandlercmbFunctionArea_SelectedIndexChanged);


//Create the String array object, initialize the array with the column
//names to be displayed
arrstrFunctionalArea          = new string [3];
arrstrFunctionalArea[0]       = "Functional Area";
arrstrFunctionalArea[1]       = "Min";
arrstrFunctionalArea[2]       = "Max";


//Create the Data Table object which will then be used to hold
//columns and rows
dtblFunctionalArea            = new DataTable ("FunctionArea");

      //Add the string array of columns to the DataColumn object       
for(int i=0; i< 3;i++)
string str        = arrstrFunctionalArea[i];
dtCol             = new DataColumn(str);
dtCol.DataType          = System.Type.GetType("System.String");
dtCol.DefaultValue      = "";

      //Add a Column with checkbox at last in the Grid     
      DataColumn dtcCheck    = new DataColumn("IsMandatory");//create the data          //column object with the name 
      dtcCheck.DataType      = System.Type.GetType("System.Boolean");//Set its //data Type
dtcCheck.DefaultValue  = false;//Set the default value
      dtblFunctionalArea.Columns.Add(dtcCheck);//Add the above column to the //Data Table

//Set the Data Grid Source as the Data Table createed above
dgdFunctionArea.DataSource    = dtblFunctionalArea; 

//set style property when first time the grid loads, next time onwards it //will maintain its property
//Create a DataGridTableStyle object     
DataGridTableStyle dgdtblStyle      = new DataGridTableStyle();
//Set its properties
            dgdtblStyle.MappingName            = dtblFunctionalArea.TableName;//its table name of dataset
dgdtblStyle.RowHeadersVisible       = false;
dgdtblStyle.HeaderBackColor         = Color.LightSteelBlue;
dgdtblStyle.AllowSorting            = false;
dgdtblStyle.HeaderBackColor         = Color.FromArgb(8,36,107);
dgdtblStyle.RowHeadersVisible       = false;
dgdtblStyle.HeaderForeColor         = Color.White;
dgdtblStyle.HeaderFont              = new System.Drawing.Font("Microsoft Sans Serif", 9F,  
                System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
dgdtblStyle.GridLineColor           = Color.DarkGray;
dgdtblStyle.PreferredRowHeight            = 22;
dgdFunctionArea.BackgroundColor           = Color.White; 

//Take the columns in a GridColumnStylesCollection object and set //the size of the
//individual columns   
GridColumnStylesCollection    colStyle;
colStyle                = dgdFunctionArea.TableStyles[0].GridColumnStyles;
colStyle[0].Width             = 100;
colStyle[1].Width       = 50;
colStyle[2].Width       = 50;
colStyle[3].Width       = 80;


//To add the combo box dynamically to the data grid, you have to take the // Text Box that is present (by default) in the column where u want to add //this combo box (here it is first column i.e. Functional Area).From the //tablestyles of the data grid take the grid column styles of the column //where you want to add the combo box respectively.

            DataGridTextBoxColumn dgtb    =     (DataGridTextBoxColumn)dgdFunctionArea.TableStyles[0].GridColumnStyles[0];

      //Add the combo box to the text box taken in the above step


dgtb.TextBox.Controls.Add (cmbFunctionArea);   

Note:-//After these add the code to fill the details in the grid by //establishing
// connection to the server and writing necessary steps: 

  }//end of the class

}//end of the namespace


Fig below depicts the concept discussed above:

Figure 1:   Adding Rows,Columns and Controls Dynamically to the Data



Combo Box Control Added to the Functional Area Column (For each Row) dynamically. 

How to Add Check Boxes to a DataGrid

//call this below method after initialize component


private void PopulateShortlistGrid()


DataColumn        dtcShortlist;

//Combo box control added as discussed above   

cmbWorkflow                   = new ComboBox();

cmbWorkflow.Cursor            = System.Windows.Forms.Cursors.Arrow;

cmbWorkflow.DropDownStyle     = System.Windows.Forms.ComboBoxStyle.DropDownList;

cmbWorkflow.Dock              = DockStyle.Fill;

dtbShortlist                  = new DataTable("ShortList");

strColumnName          = null;

string []arrstrSearch         = null;

arrstrSearch                  = new string[4];

arrstrSearch[1]               = "Candidate Code";

arrstrSearch[2]               = "Candidate Name";
arrstrSearch[3]               = "Workflow";

//Adding a check box control in the first column of the data grid

//create a Data Column object with Column Name as ?Select?span style="mso-tab-count:1"> 

DataColumn  dtcCheck          = new DataColumn("Select");

//Set the data type of the checkbox i.e. to Boolean

dtcCheck.DataType             = System.Type.GetType("System.Boolean");

//Set its default value as false

dtcCheck.DefaultValue         = false;

//add the above check box column to the data table


//Also add the other three columns i.e. Candidate Code, Candidate //Name and Workflow respectively

(int intI=1; intI< 4;intI++)

strColumnName     = arrstrSearch[intI];

dtcShortlist      = new DataColumn(strColumnName);

dtcShortlist.DataType = System.Type.GetType("System.String");   

dgdShortList.DataSource       = dtbShortlist; 




                        Figure below depicts the above discussion:



Figure: Added as the first column to the Data Grid  

Focusing a particular cell in the Data Grid


To focus a particular cell in the grid created above, you have to focus on the TextBox Control that is present in each cell of the DataGrid created above. To take the text box present in the grid cell which u want to focus, follow the steps followed below:

//Bring the focus to the grid in which the cell is present (where u want //the focus)



//Create a DataGrid Cell object and take the Cell by passing Row and //Column number respectively

DataGridCell dgc = new DataGridCell(1,1); //here it is 2ndrow, 2nd Column 

//Make the current cell of the grid as the cell u have taken above i.e. 
//the cell where u need the focus to be 
dgdLoad.CurrentCell = dgc; 
//To take the text Box of the cell where u want the focus to be take 
//it from the Table Styles of the grid and in that the column style 
 //by passing the column number where u wants the focus to be   
DataGridTextBoxColumn dgtb = (DataGridTextBoxColumn)dgdLoad.TableStyles[0].GridColumnStyles[2];

//Focus on the text box i.e. in turn on cell where u need the focus 



Figure below signifies the above concept:

Fig 2: Focus to the particular cell in a Data Grid




About the Author:
Tushar Ameta is an engineering graduate. He is working with a Software MNC in Bangalore,India. He has been working on the .NET and C# for the past 10 months.

Any queries welcome: Email id:

HDU 1988 Cube Stacking (数据结构-并查集)

HDU 1988 Cube Stacking (数据结构-并查集) 题目大意: 有N个立方体和N个格子,1~N编号,一开始i立方体在i号格子上,每个格子刚好1个立方体。现在m组操作,M a b表示将...
  • a1061747415
  • a1061747415
  • 2014年07月30日 11:42
  • 1500


compatible也能降 compatible也能由高变低,不过是在9i。 今天在看oracle 10g的文档,注意到Irreversible Compatibility这个说法。 S...
  • haiross
  • haiross
  • 2014年01月15日 11:59
  • 4397

VC DataGrid控件使用总结

MS CDataGrid控件用法详解 本文示例源代码或素材下载 。DataGrid控件是VC方便地用来显示数据的一个极好的网格控件,我不否认网上还有期它不少优秀的网格控件,但我总喜欢使用微...
  • bcbobo21cn
  • bcbobo21cn
  • 2016年04月01日 18:37
  • 1678

FOJ Playing with Calculator (模运算)

Problem Description Pete is playing a game. He types on a calculator a natural number K and then ...
  • ShiWaiGaoRen12345
  • ShiWaiGaoRen12345
  • 2016年08月15日 22:12
  • 147

527A. Playing with Paper【math】

A. Playing with Paper time limit per test 2 seconds memory limit per test 256 megabytes i...
  • u014787301
  • u014787301
  • 2015年03月21日 18:33
  • 511

Playing with ptrace, Part I

Nov 01, 2002  By Pradeep Padala  in SysAdmin Using ptrace allows you to set up system call ...
  • starstarstone
  • starstarstone
  • 2012年04月26日 11:10
  • 346

programming-challenges Playing with Wheels (110902) 题解

一开始居然没想到bfs。 #include #include #include #include #include #include #include #include #inclu...
  • houhouzhe
  • houhouzhe
  • 2015年11月03日 22:59
  • 255

Playing with huge information streams: Twitter Storm!

Past Christmas I found the perfect pet project for that season: Twitter Storm. Basically is a e...
  • macyang
  • macyang
  • 2012年02月06日 21:24
  • 976

Playing with Virtual Memory

文章来源:  很赞的一篇文章! Whe...
  • macyang
  • macyang
  • 2011年09月01日 22:43
  • 790

Nim游戏的一个扩展——51nod 1661 黑板上的游戏+LA 5059 Playing With Stones

前几天做过一道题目,是Nim游戏的一个扩展,也不能说扩展吧,只是说另一种常见的状态。 问题引入: 给定n堆石子,每堆石子有vi(1 思考: 当k==2的时候,显然就退化成了la 5059 ...
  • bobodem
  • bobodem
  • 2016年08月30日 21:11
  • 332
您举报文章:Playing with DataGrid Control