A simple home-made StringGrid

T

Tal Sharfi

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
(e-mail address removed)

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.
/// (e-mail address removed)
///
/// 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(newEnt),
this.dataGrid1.CurrentRowIndex);
newEnt = new PhoneBookEntry("david", "5553333");
this.dataGrid1.InsertAt(this.converObjToDataRow(newEnt),
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("System.Object"),
"Name", true);
this.dataGrid1.addColumn(System.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 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.dataGrid1)).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_CurrentCellChanged);
//
// 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.dataGrid1)).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.CurrentRowIndex);
// 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();

}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top