Hi everyone
I recently had the need for StringGrid object same as the one that
Delphi has. An object that helps show lists of other objects in a
simple grid. I searched the news groups and found none, so, I wrote
one and decided to share it with you.
It's a very simple one with few functions. I derived a DataGrid and
added to it a DataTable to hold the data. The object itself is
handling the synchronization between them, because some of the
operations are relevant to the StringGrid and some to the DataTable.
I added a simple program that shows how to work with it. You are all
free to use it and if you adding something that you think could help,
please publish also.
Enjoy,
Tal Sharfi
ta******@hotmai l.com
The file:
1. StringGrid.cs: the string grid object itself
2. PhoneBookEntry. cs: a test object to be used in the example
3. Form1.cs: the form to run the example
/////////////////////////////////////////////////////////////////////
1. StringGrid.cs: the string grid object itself
/////////////////////////////////////////////////////////////////////
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Drawing;
using System.Data;
using System.Windows. Forms;
namespace StringGridExmpl {
/// <summary>
/// StringGrid object by: Tal Sharfi.
/// ta******@hotmai l.com
///
/// a very elementry strignGrid object that inherits from DataGrid
and uses a DataTable object to save
/// it's data. the strignGrid handles the synchronization between
the objects in order to get a covinient
/// work-flow in the forms that uses this object.
///
/// you may add, change, as much as you want, just be kind to share.
/// </summary>
public class StringGrid : System.Windows. Forms.DataGrid {
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;
private System.Data.Dat aTable mDataTable;
public StringGrid() {
InitializeCompo nent();
mDataTable = new DataTable("Pare ntTable");
}
public void addColumn(Syste m.Type fColType, string fColName, bool
fReadonly){
// Declare variables for DataColumn and DataRow objects.
DataColumn aDataColumn;
aDataColumn = new DataColumn();
aDataColumn.Dat aType = fColType;
aDataColumn.Col umnName = fColName;
aDataColumn.Rea dOnly = fReadonly;
mDataTable.Colu mns.Add(aDataCo lumn);
}
public void activate(){
// Instantiate the DataSet variable.
DataSet myDataSet = new DataSet();
// Add the new DataTable to the DataSet.
myDataSet.Table s.Add(mDataTabl e);
this.DataSource = this.mDataTable ;
}
/// <summary>
/// remove the selected row(record) from the grid
/// </summary>
public void RemoveSelectedR ow(){
mDataTable.Rows .RemoveAt(this. CurrentRowIndex );
mDataTable.Acce ptChanges();
}
/// <summary>
/// add a new datarow to the string grid
/// </summary>
/// <param name="fNewRow"> the new dataRow</param>
public void AddRow(DataRow fNewRow){
mDataTable.Rows .Add(fNewRow);
}
/// <summary>
/// exposing the dataTable's newRow method
/// </summary>
/// <returns></returns>
public DataRow NewRow(){
return mDataTable.NewR ow();
}
/// <summary>
/// replace the requested row with a new row
/// </summary>
/// <param name="fNewRow"> the new row to put insted the old
one</param>
/// <param name="fIndex">t he index of the replaced row</param>
public void ReplaceAt(DataR ow fNewRow, int fIndex){
this.mDataTable .Rows.RemoveAt( fIndex);
this.mDataTable .Rows.InsertAt( fNewRow, fIndex);
this.mDataTable .AcceptChanges( );
}
/// <summary>
/// replace the current selected row
/// </summary>
/// <param name="fNewRow"> the new row</param>
public void ReplaceAtSelect ed(DataRow fNewRow){
ReplaceAt(fNewR ow, this.CurrentRow Index);
}
public void InsertAt(DataRo w fRow, int fIndex){
if(fIndex <= -1)
fIndex = 0;
mDataTable.Rows .InsertAt(fRow, fIndex);
mDataTable.Acce ptChanges();
}
/// <summary>
/// returns the number of rows in the string grid
/// </summary>
/// <returns>the number of rows in the string grid</returns>
public int RowsCount{
get{ return this.mDataTable .Rows.Count; }
}
/// <summary>
/// clear all rows from the string grid
/// </summary>
public void ClearAll(){
this.mDataTable .Rows.Clear();
}
/// <summary>
/// get the cell content
/// </summary>
/// <param name="fRow">the cell's row</param>
/// <param name="fColumn"> the cell's column</param>
/// <returns></returns>
public object Cell(int fRow, int fColumn){
return this.mDataTable .Rows[fRow][fColumn];
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing ) {
if( disposing ) {
if(components != null) {
components.Disp ose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent() {
//
// StringGrid
//
this.Name = "StringGrid ";
this.Size = new System.Drawing. Size(296, 224);
}
#endregion
}
}
/////////////////////////////////////////////////////////////////////
2. PhoneBookEntry. cs: a test object to be used in the example
/////////////////////////////////////////////////////////////////////
using System;
using System.Collecti ons;
using System.Data;
namespace StringGridExmpl {
/// <summary>
/// a simple phonebook entry with a name and a phone number
/// </summary>
public class PhoneBookEntry {
public string Name;
public string Phone;
public PhoneBookEntry( string fName, string fPhone) {
Name = fName;
Phone = fPhone;
}
}
}
/////////////////////////////////////////////////////////////////////
3. Form1.cs: the form to run the example
/////////////////////////////////////////////////////////////////////
using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.Data;
namespace StringGridExmpl {
/// <summary>
/// example form for the stringGrid object
/// show some elemetary operations with it.
/// pay attantion that the form has to manage the creation of the
columns and handle the conversion
/// of the saved object (the object that will be shown in the string
grid) into a dataRow object which
/// is the object that the stringGrid ia actually workign with
/// </summary>
public class Form1 : System.Windows. Forms.Form {
private StringGridExmpl .StringGrid dataGrid1;
private System.Windows. Forms.TextBox txtName;
private System.Windows. Forms.TextBox txtPhone;
private System.Windows. Forms.Label label1;
private System.Windows. Forms.Label label2;
private System.Windows. Forms.Button btnAddAsNew;
private System.Windows. Forms.Button btnDelete;
private System.Windows. Forms.Button btnUpdate;
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;
public Form1() {
InitializeCompo nent();
// special init function for the string grid.
InitStringGrid( );
// add some example data
PhoneBookEntry newEnt = new PhoneBookEntry( "moshe", "5553453");
this.dataGrid1. InsertAt(this.c onverObjToDataR ow(newEnt),
this.dataGrid1. CurrentRowIndex );
newEnt = new PhoneBookEntry( "david", "5553333");
this.dataGrid1. InsertAt(this.c onverObjToDataR ow(newEnt),
this.dataGrid1. CurrentRowIndex );
}
/// <summary>
/// init the stringGrid
/// must be match with the "converObjToDat aRow" function below.
/// just add to the stringGrid the columns that will be shown.
/// </summary>
private void InitStringGrid( ){
// creat the datatable
this.dataGrid1. addColumn(Syste m.Type.GetType( "System.Object" ),
"Name", true);
this.dataGrid1. addColumn(Syste m.Type.GetType( "System.Object" ),
"Phone", true);
this.dataGrid1. activate();
}
/// <summary>
/// take an object and convert it to a dataRow object in order to
insert it into the string grid.
/// the conversion must be matched with the addColumns commands
above when initializing the stringGrid.
/// pay notice that the function asks for the stringGrid object for
a new DataRow Object.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private DataRow converObjToData Row(object obj){
PhoneBookEntry ent = obj as PhoneBookEntry;
DataRow myDataRow = null;
if(ent != null){
myDataRow = this.dataGrid1. NewRow();
myDataRow["Name"] = ent.Name;
myDataRow["Phone"] = ent.Phone;
}
return myDataRow;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing ) {
if( disposing ) {
if (components != null) {
components.Disp ose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent() {
this.dataGrid1 = new StringGridExmpl .StringGrid();
this.txtName = new System.Windows. Forms.TextBox() ;
this.txtPhone = new System.Windows. Forms.TextBox() ;
this.label1 = new System.Windows. Forms.Label();
this.label2 = new System.Windows. Forms.Label();
this.btnAddAsNe w = new System.Windows. Forms.Button();
this.btnDelete = new System.Windows. Forms.Button();
this.btnUpdate = new System.Windows. Forms.Button();
((System.Compon entModel.ISuppo rtInitialize)(t his.dataGrid1)) .BeginInit();
this.SuspendLay out();
//
// dataGrid1
//
this.dataGrid1. DataMember = "";
this.dataGrid1. HeaderForeColor =
System.Drawing. SystemColors.Co ntrolText;
this.dataGrid1. Location = new System.Drawing. Point(88, 48);
this.dataGrid1. Name = "dataGrid1" ;
this.dataGrid1. Size = new System.Drawing. Size(424, 160);
this.dataGrid1. TabIndex = 0;
this.dataGrid1. CurrentCellChan ged += new
System.EventHan dler(this.dataG rid1_CurrentCel lChanged);
//
// txtName
//
this.txtName.Lo cation = new System.Drawing. Point(192, 248);
this.txtName.Na me = "txtName";
this.txtName.Ta bIndex = 1;
this.txtName.Te xt = "";
//
// txtPhone
//
this.txtPhone.L ocation = new System.Drawing. Point(192, 288);
this.txtPhone.N ame = "txtPhone";
this.txtPhone.T abIndex = 2;
this.txtPhone.T ext = "";
//
// label1
//
this.label1.Loc ation = new System.Drawing. Point(96, 248);
this.label1.Nam e = "label1";
this.label1.Siz e = new System.Drawing. Size(72, 24);
this.label1.Tab Index = 3;
this.label1.Tex t = "Name:";
//
// label2
//
this.label2.Loc ation = new System.Drawing. Point(96, 288);
this.label2.Nam e = "label2";
this.label2.Siz e = new System.Drawing. Size(64, 16);
this.label2.Tab Index = 4;
this.label2.Tex t = "Phone:";
//
// btnAddAsNew
//
this.btnAddAsNe w.Location = new System.Drawing. Point(352, 248);
this.btnAddAsNe w.Name = "btnAddAsNe w";
this.btnAddAsNe w.Size = new System.Drawing. Size(120, 24);
this.btnAddAsNe w.TabIndex = 5;
this.btnAddAsNe w.Text = "Add As New";
this.btnAddAsNe w.Click += new
System.EventHan dler(this.btnAd dAsNew_Click);
//
// btnDelete
//
this.btnDelete. Location = new System.Drawing. Point(528, 248);
this.btnDelete. Name = "btnDelete" ;
this.btnDelete. Size = new System.Drawing. Size(112, 24);
this.btnDelete. TabIndex = 6;
this.btnDelete. Text = "Delete Selected";
this.btnDelete. Click += new
System.EventHan dler(this.btnDe lete_Click);
//
// btnUpdate
//
this.btnUpdate. Location = new System.Drawing. Point(352, 288);
this.btnUpdate. Name = "btnUpdate" ;
this.btnUpdate. Size = new System.Drawing. Size(120, 23);
this.btnUpdate. TabIndex = 0;
this.btnUpdate. Text = "Update";
this.btnUpdate. Click += new
System.EventHan dler(this.btnUp date_Click);
//
// Form1
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.ClientSize = new System.Drawing. Size(656, 414);
this.Controls.A dd(this.btnUpda te);
this.Controls.A dd(this.btnDele te);
this.Controls.A dd(this.btnAddA sNew);
this.Controls.A dd(this.label2) ;
this.Controls.A dd(this.label1) ;
this.Controls.A dd(this.txtPhon e);
this.Controls.A dd(this.txtName );
this.Controls.A dd(this.dataGri d1);
this.Name = "Form1";
this.Text = "Form1";
((System.Compon entModel.ISuppo rtInitialize)(t his.dataGrid1)) .EndInit();
this.ResumeLayo ut(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.Run (new Form1());
}
// some basic operations...
// add new phoneBook entry.
private void btnAddAsNew_Cli ck(object sender, System.EventArg s e) {
// create a new object
PhoneBookEntry newEnt = new PhoneBookEntry( this.txtName.Te xt,
this.txtPhone.T ext);
// convert the object to a proper DataRow object
DataRow dataRow = this.converObjT oDataRow(newEnt );
// insert the new object (datarow) into the stringGrid
this.dataGrid1. InsertAt(dataRo w, this.dataGrid1. CurrentRowIndex );
}
// update, actully, it's over writing the old one...
private void btnUpdate_Click (object sender, System.EventArg s e) {
// same as above...
PhoneBookEntry newEnt = new PhoneBookEntry( this.txtName.Te xt,
this.txtPhone.T ext);
DataRow dataRow = this.converObjT oDataRow(newEnt );
// replace the current row with the new one
this.dataGrid1. ReplaceAtSelect ed(dataRow);
}
// catch the event that marks for moving between the records
private void dataGrid1_Curre ntCellChanged(o bject sender,
System.EventArg s e) {
this.dataGrid1. Select(this.dat aGrid1.CurrentR owIndex);
// read the current selected row into the textboxes
this.txtName.Te xt = this.dataGrid1. Cell(dataGrid1. CurrentRowIndex ,
0).ToString();
this.txtPhone.T ext = this.dataGrid1. Cell(dataGrid1. CurrentRowIndex ,
1).ToString();
}
// delete a row
private void btnDelete_Click (object sender, System.EventArg s e) {
this.dataGrid1. RemoveSelectedR ow();
}
}
}