473,390 Members | 1,447 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,390 software developers and data experts.

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******@hotmail.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.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace StringGridExmpl {
/// <summary>
/// StringGrid object by: Tal Sharfi.
/// ta******@hotmail.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.ComponentModel.Container components = null;
private System.Data.DataTable mDataTable;

public StringGrid() {
InitializeComponent();
mDataTable = new DataTable("ParentTable");
}

public void addColumn(System.Type fColType, string fColName, bool
fReadonly){
// Declare variables for DataColumn and DataRow objects.
DataColumn aDataColumn;

aDataColumn = new DataColumn();
aDataColumn.DataType = fColType;
aDataColumn.ColumnName = fColName;
aDataColumn.ReadOnly = fReadonly;
mDataTable.Columns.Add(aDataColumn);
}
public void activate(){
// Instantiate the DataSet variable.
DataSet myDataSet = new DataSet();
// Add the new DataTable to the DataSet.
myDataSet.Tables.Add(mDataTable);

this.DataSource = this.mDataTable;
}
/// <summary>
/// remove the selected row(record) from the grid
/// </summary>
public void RemoveSelectedRow(){
mDataTable.Rows.RemoveAt(this.CurrentRowIndex);
mDataTable.AcceptChanges();
}
/// <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.NewRow();
}
/// <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">the index of the replaced row</param>
public void ReplaceAt(DataRow 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 ReplaceAtSelected(DataRow fNewRow){
ReplaceAt(fNewRow, this.CurrentRowIndex);
}
public void InsertAt(DataRow fRow, int fIndex){
if(fIndex <= -1)
fIndex = 0;
mDataTable.Rows.InsertAt(fRow, fIndex);
mDataTable.AcceptChanges();
}
/// <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.Dispose();
}
}
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 InitializeComponent() {
//
// 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.Collections;
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.Collections;
using System.ComponentModel;
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.ComponentModel.Container components = null;

public Form1() {

InitializeComponent();

// special init function for the string grid.
InitStringGrid();

// add some example data
PhoneBookEntry newEnt = new PhoneBookEntry("moshe", "5553453");
this.dataGrid1.InsertAt(this.converObjToDataRow(ne wEnt),
this.dataGrid1.CurrentRowIndex);
newEnt = new PhoneBookEntry("david", "5553333");
this.dataGrid1.InsertAt(this.converObjToDataRow(ne wEnt),
this.dataGrid1.CurrentRowIndex);

}

/// <summary>
/// init the stringGrid
/// must be match with the "converObjToDataRow" function below.
/// just add to the stringGrid the columns that will be shown.
/// </summary>
private void InitStringGrid(){
// creat the datatable
this.dataGrid1.addColumn(System.Type.GetType("Syst em.Object"),
"Name", true);
this.dataGrid1.addColumn(System.Type.GetType("Syst em.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 converObjToDataRow(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.Dispose();
}
}
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 InitializeComponent() {
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.btnAddAsNew = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnUpdate = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.d ataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor =
System.Drawing.SystemColors.ControlText;
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.CurrentCellChanged += new
System.EventHandler(this.dataGrid1_CurrentCellChan ged);
//
// txtName
//
this.txtName.Location = new System.Drawing.Point(192, 248);
this.txtName.Name = "txtName";
this.txtName.TabIndex = 1;
this.txtName.Text = "";
//
// txtPhone
//
this.txtPhone.Location = new System.Drawing.Point(192, 288);
this.txtPhone.Name = "txtPhone";
this.txtPhone.TabIndex = 2;
this.txtPhone.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(96, 248);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 24);
this.label1.TabIndex = 3;
this.label1.Text = "Name:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(96, 288);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(64, 16);
this.label2.TabIndex = 4;
this.label2.Text = "Phone:";
//
// btnAddAsNew
//
this.btnAddAsNew.Location = new System.Drawing.Point(352, 248);
this.btnAddAsNew.Name = "btnAddAsNew";
this.btnAddAsNew.Size = new System.Drawing.Size(120, 24);
this.btnAddAsNew.TabIndex = 5;
this.btnAddAsNew.Text = "Add As New";
this.btnAddAsNew.Click += new
System.EventHandler(this.btnAddAsNew_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.EventHandler(this.btnDelete_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.EventHandler(this.btnUpdate_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(656, 414);
this.Controls.Add(this.btnUpdate);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnAddAsNew);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtPhone);
this.Controls.Add(this.txtName);
this.Controls.Add(this.dataGrid1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.d ataGrid1)).EndInit();
this.ResumeLayout(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_Click(object sender, System.EventArgs e) {
// create a new object
PhoneBookEntry newEnt = new PhoneBookEntry(this.txtName.Text,
this.txtPhone.Text);
// convert the object to a proper DataRow object
DataRow dataRow = this.converObjToDataRow(newEnt);
// insert the new object (datarow) into the stringGrid
this.dataGrid1.InsertAt(dataRow, this.dataGrid1.CurrentRowIndex);
}

// update, actully, it's over writing the old one...
private void btnUpdate_Click(object sender, System.EventArgs e) {
// same as above...
PhoneBookEntry newEnt = new PhoneBookEntry(this.txtName.Text,
this.txtPhone.Text);
DataRow dataRow = this.converObjToDataRow(newEnt);
// replace the current row with the new one
this.dataGrid1.ReplaceAtSelected(dataRow);

}

// catch the event that marks for moving between the records
private void dataGrid1_CurrentCellChanged(object sender,
System.EventArgs e) {
this.dataGrid1.Select(this.dataGrid1.CurrentRowInd ex);
// read the current selected row into the textboxes
this.txtName.Text = this.dataGrid1.Cell(dataGrid1.CurrentRowIndex,
0).ToString();
this.txtPhone.Text = this.dataGrid1.Cell(dataGrid1.CurrentRowIndex,
1).ToString();
}

// delete a row
private void btnDelete_Click(object sender, System.EventArgs e) {
this.dataGrid1.RemoveSelectedRow();

}
}
}
Nov 16 '05 #1
0 7515

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

Similar topics

1
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...
6
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....
2
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...
2
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...
18
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">...
4
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,...
7
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,...
0
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 -...
4
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...
5
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.