473,769 Members | 3,557 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A simple home-made StringGrid

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();

}
}
}
Nov 16 '05 #1
0 7566

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3257
by: Preston Crawford | last post by:
I'm looking to quickly get a photo album online. Very simple, thumbnails, a few pages, maybe a description, but hopefully a small script that's easy to edit and work into my existing site. I know about hot scripts, etc. but I was wondering if any one could recommend one? Secondly, I also want to setup a journal. It's not really a "blog" although I guess blog software may work. But it isn't going to be a message board or anything like...
6
1702
by: Kyle E | last post by:
I wrote a program that asks a user questions and records the answers and prints them out at the end. Pretty simple... but I have a few things that I don't like about it. ---------------------------------------------- print "Do you have a P.O. Box?" poan = raw_input ("> ") if poan == "yes": print "What is your P.O. Box number?" pobox = input ("> ") ----------------------------------------------
2
1425
by: Sigma | last post by:
I have a home-network with XP Pro running on one computer and want to setup a web site on the XP machine so that I can setup ASP webs with FP server extensions - and connect to them from another home computer. I find ALL the options - choices - selections on IIs far to confusing - ( for my simple mind ) does anyone know of a site that offers very simple
2
1440
by: Sigma | last post by:
I have a home-network with XP Pro running on one computer and want to setup a web site on the XP machine so that I can setup ASP webs with FP server extensions - and connect to them from another home computer. I find ALL the options - choices - selections on IIs far to confusing - ( for my simple mind ) does anyone know of a site that offers very simple
18
3390
by: middletree | last post by:
Trying to build a dropdown from the values in an Access database, but can't get past this error. Should be easy, but I can't make it work. First, the code: 1. <select name="Gift1" id="Gift1"> <option value="" selected>-Select One- <%Set RS = Server.CreateObject("ADODB.Recordset") strSQL = "SELECT GiftID, GiftDesc " strSQL = strSQL & "FROM Gift " strSQL = strSQL & "ORDER BY GiftDesc"
4
1956
by: David | last post by:
Hello, I want to write a simple logging class. But when I instantiate the logger with Logger::logger log("log.log"); I get a "Bus Error - core dumped". Can anybody help? Thanks beforehand, David This is my logger.hpp file (I tried it with .h, too.)
7
1481
by: Michael Peters | last post by:
I need a simple editor to edit the texts in static html pages. Is there a program for that? It should be something very simple, nothing like Dreamweaver. I don't need to edit any tables, structures, etc., just the texts. -Michael
0
1242
by: mionix | last post by:
Hi I'm beginer with php. I need a favour. Could somebody show me or send to my email source code with simple home page, something like this: table with three rows: first row (headline - logo) second row (table with three columns - left, middle, right)
4
1759
by: charles | last post by:
I need to send data from a 'form' on an HTML page to an ASP page. The ASP page should 'return' a simple HTML page containing the data from any items submitted, including any hidden items. I know its probably very simple, but I am beginner. Can anyone give me some simple ASP code to do this.
5
2056
bartonc
by: bartonc | last post by:
My SOHO network has XP Home Edition clients (simple file sharing, of course). Now I need to bring an XP Pro laptop into the system that wants to connect to a domain controller. The two options I see are: 1) set up my XP Pro server to support both services or 2) set up the laptop to use simple file sharing at home and connect to the domain at work. Any suggestions, anyone? If I need to set up a domain at home, I'll need some guidance to...
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9422
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10206
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9851
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8863
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7403
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3949
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3556
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.