How to Create a Custom Control with C Sharp

Environment: Visual Studio.NET

This small project isn’t completely finish yet because I cannot load the image from the database table into a picture box and save it back to the database, but it can show you how to work with winform controls and the Data Adapter. If you do not understand any part of it, just drop me an email at cql60@yahoo.com.


PART ONE:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace WindowsApplication1
{
/// <SUMMARY>
/// Summary description for Form1.
/// </SUMMARY>

public class FirstDlg : System.Windows.Forms.Form
{
private System.Windows.Forms.TreeView treeView1;
private System.ComponentModel.IContainer components;
public UserCompositeControl CompCtrl;
public System.Windows.Forms.TreeNode root;
public System.Windows.Forms.TreeNode tableNode;
public System.Windows.Forms.TreeNode column;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Data.DataSet myDataSet;
private System.Data.DataTable myDataTable;

public FirstDlg()
{
//
// Required for Windows Form Designer support
//

InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent
// call
//

}

/// <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.SuspendLayout();
this.components = new System.ComponentModel.Container();
//
// FirstDlg
//

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(712, 433);
this.Name = “FirstDlg”;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.
CenterParent;
this.Text = “My first Dialog”;
this.WindowState = System.Windows.Forms.FormWindowState.
Maximized;
// Change the cursor to wait cursor
Cursor.Current = Cursors.WaitCursor;
// Create Popup Menu
Create_Popup_Menu();
// Create TreeView
Create_Tree();
// Create Tree Items
Initialize_Tree();
// Change the Cursor back to arrow
Cursor.Current = Cursors.Default;
// Set event handler for context menu
this.contextMenu1.Popup += new System.EventHandler(
this.PopupMenuEventHandler );
this.menuItem1.Click += new System.EventHandler(
this.MenuItemEventHandler );
this.menuItem2.Click += new System.EventHandler(
this.MenuItemEventHandler );
this.menuItem3.Click += new System.EventHandler(
this.MenuItemEventHandler );
this.ResumeLayout();
}
#endregion

private void Create_Popup_Menu()
{
// Create context menu and submenu
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
// Initialize menuItem1 properties
this.menuItem1.Index = 0;
this.menuItem1.Text = “Edit”;
// Initialize menuItem2 properties
this.menuItem2.Index = 1;
this.menuItem2.Text = “Delete”;
this.menuItem2.Visible = false;
// Initialize menuItem3 properties
this.menuItem3.Index = 2;
this.menuItem3.Text = “Insert”;
this.menuItem3.Visible = false;
// Add sub menu to context menu
this.contextMenu1.MenuItems.AddRange(new System.Windows.
Forms.MenuItem[] {this.menuItem1,
this.menuItem2,
this.menuItem3});
}

protected void PopupMenuEventHandler( System.Object sender,
EventArgs e )
{
if( this.CompCtrl.Visible == false )
{
this.menuItem1.Visible = true;
this.menuItem2.Visible = true;
this.menuItem3.Visible = true;
// Define what’s control sent command.
if( this.contextMenu1.SourceControl is ListView )
{
// Display menu items for the listview.
this.menuItem1.Text = “Edit”;
this.menuItem2.Visible = true;
this.menuItem3.Visible = true;
}
else if( this.contextMenu1.SourceControl is TabControl )
{
// Display menu items for the tab view.
this.menuItem1.Text = “Remove Tab”;
this.menuItem2.Visible = false;
this.menuItem3.Visible = false;
}
}
else
{
this.menuItem1.Visible = false;
this.menuItem2.Visible = false;
this.menuItem3.Visible = false;
}
}

private void MenuItemEventHandler(object sender,
System.EventArgs e)
{
// Get the parent container of the list
TabPage tpg = this.tabControl1.SelectedTab;
int iControl = tpg.Controls.Count;
// Retrieve Child Control
int ifound=0;
for( int ictrl=0; ictrl<ICONTROL; tabControl1.
Controls[iTab].Controls.Count if( tabpage the in
controls child Delete { ) this.tabControl1.
Controls[iTab].Name strTabName.Equals( name its by of
index looking ++iTab iTab<this.tabControl1.Controls.
Count; iTab=”0;” int for( collection thru Iterate
strTabName=”this.tabControl1.SelectedTab.Name;” string
tab selected Get e System.EventArgs sender, object
Remove_Tab( void private } this.menuItem1.
GetContextMenu().SourceControl.Visible=”false;” 0
this.menuItem1.GetContextMenu().SourceControl.Controls.
Count=”=” ); this.Remove_Tab( this.tabControl1 this.
menuItem1.GetContextMenu().SourceControl=”=” else this.
CompCtrl.Visible=”true;” ; this.CompCtrl.Update_Or_
Insert=”Update” lv.Visible=”false;” record new insert
Prepare Command Insert lv.SelectedItems[0].Remove();
to list from item deleted Remove lv.Name lv.Columns.Count,
lv, )tpg.Tag, System.Data.DataSet ( Delete_Record( table
Record return; list? an select ?Please MessageBox.Show(
lv.SelectedItems.Count=”=” this.menuItem2 sender.Equals(
Yet? Implemented ?Not ?Categories? !lv.Name.Equals(
properties items menu and listview Assign Edit
this.menuItem1 )tpg.Controls[ifound]; System.Windows.
Forms.ListView lv=”(” ListView tpg.Name this.menuItem1.
GetContextMenu().SourceControl.Name.Equals( message send
which source control Check break; ifound=”ictrl;” tpg.
Controls[ictrl].Name.Equals( ++ictrl> 0 )
{
tabControl1.Controls[iTab].Controls.Clear();
}
// Delete tabpage from the collection
this.tabControl1.Controls.RemoveAt( iTab );
break;
}
}
}

private void Create_Tree()
{
// Create Image
this.imageList1 = new System.Windows.Forms.ImageList(
this.components);
this.imageList1.ColorDepth = System.Windows.Forms.
ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.TransparentColor = System.Drawing.Color.
Transparent;
this.imageList1.Images.Add( new Icon( “CLSDFOLD.ICO” ) );
this.imageList1.Images.Add( new Icon( “OPENFOLD.ICO” ) );

// Create Tree
this.treeView1 = new System.Windows.Forms.TreeView();
this.treeView1.AllowDrop = true;
this.treeView1.BackColor = System.Drawing.SystemColors.
GrayText;
this.treeView1.Dock = System.Windows.Forms.DockStyle.Left;
this.treeView1.HideSelection = false;
this.treeView1.HotTracking = true;
this.treeView1.ImageList = this.imageList1;
this.treeView1.Name = “treeView1”;
this.treeView1.ShowLines = false;
treeView1.Width = this.ClientSize.Width / 3;
treeView1.TabIndex = 0;
this.treeView1.DoubleClick += new System.EventHandler(this.
treeView1_DoubleClick);
this.treeView1.DragEnter += new System.Windows.Forms.
DragEventHandler(this.
treeView1_DragEnter);
this.treeView1.ItemDrag += new System.Windows.Forms.
ItemDragEventHandler(this.
treeView1_ItemDrag);

// Create panel and intitialize its properties.
splitter1 = new System.Windows.Forms.Splitter();
// Setting properties of each control
splitter1.Location = new System.Drawing.Point(200, 0);
splitter1.Size = new System.Drawing.Size(3, 273);
// Use a different color to distinguish the two splitters.
splitter1.BackColor = Color.Blue;
splitter1.TabIndex = 1;
// Set TabStop to false for ease of use when negotiating the
// user interface.

splitter1.TabStop = false;

// Create panel and intitialize its properties.
panel1 = new System.Windows.Forms.Panel();
panel1.Dock = System.Windows.Forms.DockStyle.Fill;
panel1.TabIndex = 2;
// The order of the controls add into the collection in this
// call is critical.

this.Controls.AddRange(new System.Windows.Forms.Control[]
{this.panel1,
this.splitter1,
this.treeView1} );
// Create Tab control Panel
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.ContextMenu = contextMenu1;
this.tabControl1.Visible = false;
// Add Tab control Panel to the control collection
this.panel1.Controls.AddRange(new System.Windows.Forms.
Control[] {this.tabControl1} );
}

private void Initialize_Tree()
{
root = this.treeView1.Nodes.Add( “Database” );
// When passed as reference, variable must be initialized
string strAccessConn = “”;
// Get Schema table
DataTable dtTable = OpenDatabase( ref strAccessConn );
// Query string
string strTemp = “SELECT * FROM “, strAccessSelect;

// Create Access objects:
OleDbConnection myAccessConn = new OleDbConnection(
strAccessConn );
OleDbCommand myAccessCommand = new OleDbCommand(
“”, myAccessConn );
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(
myAccessCommand );

// Create the dataset and DataTable
myDataSet = new DataSet();
//List the table name from each row in the schema table.
for( int i=0; i<DTTABLE.ROWS.COUNT; if( the { ) name by of
string } ); new to table <summary this.tabControl1.
Tag=”myDataAdapter;” myAccessConn.Close(); dtTable.
Rows.Count (i+1)=”=” Database Close finally
dtTable.Rows[i].ItemArray[2].ToString() tableNode,
myDataSet, this.InsertTree_ChildItem( node tablenode
under column add this.tableNode.Tag=”myDataSet;”
this.tableNode=”root.Nodes.Add(” root tree
myDataAdapter.Fill( DataSet ResultSets fill try
myAccessConn.Open(); i=”=0″ Open myDataAdapter.
SelectCommand.CommandText=”strAccessSelect;”
query OleDbDataAdapter?s Reassign +=”dtTable.Rows[i].
ItemArray[2].ToString();” strAccessSelect=”strTemp;”
on base Query Build {myDataTable} DataTable[] myDataSet.
Tables.AddRange( Collection datatable Add DataTable(
myDataTable=”new” TABLE_TYPE 4_ TABLE_NAME, 3_
TABLE_SCHEMA, 2_ TABLE_CATALOG, 1_ : Restriction
ItemArray accessing Create i++>
/// Return DataTable
/// </SUMMARY>

protected DataTable OpenDatabase( ref string strAccessConn )
{
#if USINGPROJECTSYSTEM
strAccessConn = “Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=..\..\NWind.mdb”;
#else
strAccessConn = “Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\C# Project\WindowsApplication1
\NWind.mdb”;
#endif
// Create Access objects:
OleDbConnection OleConn = new OleDbConnection(
strAccessConn );
// Open Database
OleConn.Open();
// Get Schema Table
DataTable schemaTable = OleConn.GetOleDbSchemaTable(
OleDbSchemaGuid.Tables,
new object[] {null, null, null, “TABLE”} );
// Close Connection
OleConn.Close();

return schemaTable;
}

private void treeView1_DoubleClick(object sender,
System.EventArgs e)
{
// Change the image to Open icon
if( this.treeView1.SelectedNode.IsExpanded )
this.treeView1.SelectedNode.SelectedImageIndex = 1;
else // Change the image to Close icon
this.treeView1.SelectedNode.SelectedImageIndex = 0;

// Get data of double clicked node
if( this.treeView1.SelectedNode.Tag != null &&
this.treeView1.SelectedNode.Tag.GetType().Name.Equals(
“DataSet” ) )
{
this.tabControl1.Visible = true;
Create_Tab_Page( this.treeView1.SelectedNode );
}
}

private void InsertTree_ChildItem( DataSet dtset,
TreeNode table,
string strTableName )
{
// Retrieve Column name from the table
try
{
// Retrieve column object collection from the table
DataColumnCollection drc = dtset.Tables[strTableName].
Columns;
foreach( DataColumn dc in drc )
{
// add column name under tablenode node.
table.Nodes.Add( dc.ColumnName );
}
}
catch( Exception Err )
{
MessageBox.Show( Err.Message );
}
}

private void treeView1_ItemDrag(object sender,
System.Windows.Forms.ItemDragEventArgs e)
{
DoDragDrop(e.Item.ToString(), DragDropEffects.Link |
DragDropEffects.Move);
}

private void treeView1_DragEnter(object sender, System.Windows.
Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Link;
}

private void Create_Tab_Page( TreeNode nodeParent )
{
// Check to see is it this tabpage already created
TabControl.TabPageCollection tpColl =
this.tabControl1.TabPages;
foreach( TabPage tp in tpColl )
{
if( tp.Name.Equals( nodeParent.Text ) )
return;
}
// Create Tabpage
this.tabPage1 = new TabPage( nodeParent.Text );
this.tabPage1.Name = nodeParent.Text;
this.tabPage1.Tag = nodeParent.Tag;
// Adds the tabPage1 to this collection.
this.tabControl1.Controls.AddRange( new System.Windows.
Forms.Control[]{
tabPage1 } );
this.tabControl1.ContextMenu = contextMenu1;
Create_List( this.tabPage1, nodeParent );
}

private void Create_List( TabPage tpg, TreeNode ParentNode )
{
// Create Listview
this.listView1 = new ListView();
// Bind list view to its parent
this.listView1.Bounds = tpg.ClientRectangle;;
// Set the view to show details.
this.listView1.View = View.Details;
// Allow the user to edit item text.
this.listView1.LabelEdit = false;
// Allow the user to rearrange columns.
this.listView1.AllowColumnReorder = true;
// Display check boxes.
this.listView1.CheckBoxes = true;
// Select the item and subitems when selection is made.
this.listView1.FullRowSelect = true;
// Display grid lines.
this.listView1.GridLines = true;
// Sort the items in the list in ascending order.
this.listView1.Sorting = SortOrder.Ascending;
// Not allow multi selection
this.listView1.MultiSelect = false;
// Set the name of list
this.listView1.Name = ParentNode.Text;
// Docking
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
// Set context menu of the list box
this.listView1.ContextMenu = contextMenu1;
// Iterate throught the parent node to retrieve the table’s
// column name

for( int iNode=0; iNode<PARENTNODE.GETNODECOUNT( if( the in
controls { ) of int for( collection string void private
} 0 ); else this.CompCtrl.Visible=”false;” new to list
from item=”new” lv, System.Data.DataSet ( Delete_Record(
table MessageBox.Show( ?Categories? items and listview
ListView control Check break; finally node column add
tree DataSet try Collection Add Create ds.Tables
[strName].ChildRelations.Count this with other
relationship childRows; DataRow[] nRows=”0;” )this.
tabControl1.Tag; OleDbDataAdapter dbadapter=”(”
OleDbCommand Retrieve iRowCount++; ds.Tables[strName].
AcceptChanges(); datarow[iRowCount].Delete(); on… so
row second is datarow[1] row, first datarow[0] lv.
SelectedItems[0].Text dtRow[0].ToString().Equals(
dtRow[1] column, dtRow[0] datarow=”dataset.Tables[
ParentNode.Text].Rows;” dtRow DataRow foreach(
iRowCount=”0;” DataRowCollection rows total strName
iColumn, ds, listView1 tpg.Controls.Add( collection.
CompCtrl Control this.CompCtrl.Dock=”System.Windows.
Forms.DockStyle.Left;” UserCompositeControl(); this.
CompCtrl=”new” Composite intitialize ParentNode.Text.
Equals( Err.Message Err) (Exception catch ++iRow;
ListViewItem[]{item} this.listView1.Items.AddRange(
true ParentNode.GetNodeCount( iCol+1 Item dtRow[iCol].
ToString() item.SubItems.Add( item.Tag=”dtRow[iCol];”
?Picture? ?System.Byte[]? dtRow[iCol].GetType().
ToString().Equals( sub data item.Text=”dtRow[iCol].
ToString();” iCol=”0;” ++iCol iCol<ParentNode.
GetNodeCount( ListViewItem(); iRow=”0;” item;
ListViewItem item. each for subitems sets three
dataset?s Rows )ParentNode.Tag; dataset=”(” property tag
Dataset HorizontalAlignment.Left -2, ParentNode.Nodes[
iNode].Text, listView1.Columns.Add( subitems. columns
++iNode> 0 )
{
foreach( DataRelation dtrel in ds.Tables[strName].
ChildRelations )
{
foreach( DataRow dtrow in ds.Tables[strName].Rows)
{
childRows = dtrow.GetChildRows( dtrel );
}
}
}

// Create delete command
string strDelete = string.Format( “DELETE * FROM {0}”,
strName );
strDelete += string.Format( ” WHERE ({0} = {1})”,
lv.Columns[0].Text, lv.SelectedItems[0].
Text );
// Assign Delete Command with Select Command
dbadapter.DeleteCommand = dbadapter.SelectCommand;
// Set Command Text
dbadapter.DeleteCommand.CommandText = strDelete;
// Open database
dbadapter.DeleteCommand.Connection.Open();
// Execute command
nRows = dbadapter.DeleteCommand.ExecuteNonQuery();
// Close database
dbadapter.DeleteCommand.Connection.Close();
}
catch (Exception Err)
{
// In some cases, the delete command cannot delete the
// record, the catch exception will trigger, and the
// dbadapter.DeleteCommand.Connection.Close() above never
// gets to execute, so we need to do it again here

if( nRows == 0 )
dbadapter.DeleteCommand.Connection.Close();
MessageBox.Show( Err.Message );
}
}
}
}
}
END OF PART ONE

PART TWO:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsApplication1
{
/// <SUMMARY>
/// Summary description for SecondDlg.
/// </SUMMARY>

//public class UserCompositeControl :
System.Windows.Forms.Form
public class UserCompositeControl :
System.Windows.Forms.UserControl
{
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox[] Category;
private System.Windows.Forms.PictureBox CatPic;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.PictureBox pictureBox1;

/// <SUMMARY>
/// Required designer variable.
/// </SUMMARY>
//private System.ComponentModel.Container components = null;

public System.ComponentModel.Container components = null;

public UserCompositeControl()
{
//
// Required for Windows Form Designer support
//

InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent
// call
//

}

/// <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.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.Category = new System.Windows.Forms.TextBox[3];
this.Category[0] = new System.Windows.Forms.TextBox();
this.Category[1] = new System.Windows.Forms.TextBox();;
this.Category[2] = new System.Windows.Forms.TextBox();
this.CatPic = new System.Windows.Forms.PictureBox();
this.SuspendLayout();
//
// btnOK
//

this.btnOK.DialogResult = System.Windows.Forms.
DialogResult.OK;
this.btnOK.Font = new System.Drawing.Font(“Times New Roman”,
18F, System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((System.Byte)(0)));
this.btnOK.Location = new System.Drawing.Point(120, 280);
this.btnOK.Name = “btnOK”;
this.btnOK.Size = new System.Drawing.Size(88, 32);
this.btnOK.TabIndex = 3;
this.btnOK.Text = “OK”;
//
// btnCancel
//

this.btnCancel.DialogResult = System.Windows.Forms.
DialogResult.Cancel;
this.btnCancel.Font = new System.Drawing.Font(“Times
New Roman”, 18F, System.Drawing.
FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((System.Byte)(0)));
this.btnCancel.Location = new System.Drawing.Point(216, 280);
this.btnCancel.Name = “button1”;
this.btnCancel.Size = new System.Drawing.Size(88, 32);
this.btnCancel.TabIndex = 4;
this.btnCancel.Text = “Cancel”;
//
// label1
//

this.label1.Location = new System.Drawing.Point(24, 24);
this.label1.Name = “label1”;
this.label1.Size = new System.Drawing.Size(72, 16);
this.label1.TabIndex = 5;
this.label1.Text = “Category ID:”;
//
// label2
//

this.label2.Location = new System.Drawing.Point(24, 48);
this.label2.Name = “label2”;
this.label2.Size = new System.Drawing.Size(88, 16);
this.label2.TabIndex = 6;
this.label2.Text = “Category Name:”;
//
// label3
//

this.label3.Location = new System.Drawing.Point(24, 72);
this.label3.Name = “label3”;
this.label3.Size = new System.Drawing.Size(64, 16);
this.label3.TabIndex = 7;
this.label3.Text = “Description:”;
//
// label4
//

this.label4.Location = new System.Drawing.Point(24, 128);
this.label4.Name = “label4”;
this.label4.Size = new System.Drawing.Size(48, 16);
this.label4.TabIndex = 8;
this.label4.Text = “Picture:”;
//
// textBox1
//

this.Category[0].Location = new System.Drawing.Point(112, 24);
this.Category[0].Name = “CatID”;
this.Category[0].TabIndex = 9;
this.Category[0].Text = “”;
this.Category[0].Enabled = false;
//
// textBox2
//

this.Category[1].Location = new System.Drawing.Point(112, 48);
this.Category[1].Name = “CatName”;
this.Category[1].TabIndex = 10;
this.Category[1].Text = “”;
//
// textBox3
//

this.Category[2].Location = new System.Drawing.Point(112, 72);
this.Category[2].Size = new Size( 240, 12 );
this.Category[2].Name = “CatDesc”;
this.Category[2].TabIndex = 11;
this.Category[2].Text = “”;
//
// pictureBox1
//

this.CatPic.Location = new System.Drawing.Point(112, 104);
this.CatPic.Name = “pictureBox1”;
this.CatPic.Size = new System.Drawing.Size(224, 152);
this.CatPic.TabIndex = 12;
this.CatPic.TabStop = false;
this.CatPic.BorderStyle = BorderStyle.Fixed3D;
//
// UserCompositeControl
//

this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.CatPic,
this.Category[2],
this.Category[1],
this.Category[0],
this.label4,
this.label3,
this.label2,
this.label1,
this.btnCancel,
this.btnOK});
this.Name = “UserCompositeControl”;
this.Size = new System.Drawing.Size(560, 408);
this.ResumeLayout(false);
this.btnOK.Click += new System.EventHandler(
this.ButtonClickEventHandler );
this.btnCancel.Click += new System.EventHandler(
this.ButtonClickEventHandler );
this.VisibleChanged += new System.EventHandler(
this.OnVisible_Change );

}

#endregion

private void ButtonClickEventHandler( object sender,
System.EventArgs e )
{
this.Visible = false;
// Get Sender
Button btn = ( Button )sender;
// Get the parent container
TabPage tg = (TabPage)this.Parent;
// Get the parent container of the tabpage
TabControl tctrl = ( TabControl )tg.Parent;
// Retrieve OleDbCommand
System.Data.OleDb.OleDbDataAdapter dbadapter =
( System.Data.OleDb.OleDbDataAdapter )tctrl.Tag;
// Retrieve the DataSet from tabpage
System.Data.DataSet ds = ( System.Data.DataSet )tg.Tag;
// Retrieve rows from table
System.Data.DataRowCollection datarowcol =
ds.Tables[tg.Name].Rows;

//tg.Controls.
foreach( Control ct in tg.Controls )
{
// Get the name of sender
if( “btnOK” == btn.Name && ct.Name.Equals( tg.Name ))
{
if( this.strType.Equals( “Update” ) )
Update_Record( ct, datarowcol, tctrl, tg, ds );
else
Insert_Record( ct, datarowcol, tctrl, tg, ds );
}
// If the control was listview
if( ct.Name.Equals( tg.Name ) )
ct.Visible = true;
}
}

private void OnVisible_Change( object sender,
System.EventArgs e )
{
if( this.Visible == true )
{
// Get the parent container, which is tabpage
TabPage tg = (TabPage)this.Parent;
// Retrieve the child control in tabpage.
foreach( Control ct in tg.Controls )
{
// If the control was listview
if( ct.Name.Equals( tg.Name ) )
{
if( this.strType.Equals( “Update” ) )
{
ListView.SelectedListViewItemCollection
lvselectedItem =
(( ListView )ct).SelectedItems;
foreach( ListViewItem lvItem in lvselectedItem )
{
for( int i=0; i< lvItem.SubItems.Count; ++i )
{
if( (i+1) < lvItem.SubItems.Count )
this.Category[i].Text =
lvItem.SubItems[i].Text;
else
{
//System.IO.MemoryStream memstream =
//new System.IO.MemoryStream(
//(byte [])lvItem.Tag );
//this.CatPic.Image =
//System.Drawing.Image.FromStream( memstream );

}
}
}
}
}
}
}
}

// Field
public string strType;
// Get/Set Properties
public string Update_Or_Insert
{
get
{
return strType;
}
set
{
if( strType != value )
strType = value;
}
}

private void Update_Record( object objCtrl,
System.Data.DataRowCollection datarowcol,
System.Windows.Forms.TabControl tctrl,
System.Windows.Forms.TabPage tg,
System.Data.DataSet ds )
{
ListView.SelectedListViewItemCollection lvselectedItem =
(( ListView )objCtrl).SelectedItems;
foreach( ListViewItem lvItem in lvselectedItem )
{
for( int i=0; i< lvItem.SubItems.Count; ++i )
{
if( (i+1) < lvItem.SubItems.Count )
{
lvItem.SubItems[i].Text = this.Category[i].Text;
// Index of datarow in datarow collection is start from
// 1, not zero as array
// Update DataRow with new value

datarowcol[lvItem.Index][i] = this.Category[i].Text;
}
}
// Update Table
ds.Tables[tg.Name].AcceptChanges();
// Try to update database
try
{
// Retrieve OleDbDataAdapter
System.Data.OleDb.OleDbDataAdapter tempadapter =
( System.Data.OleDb.OleDbDataAdapter )tctrl.Tag;
//tempadapter.SelectCommand.CommandText =
//string.Format( “SELECT * FROM {0}”, tg.Name );

tempadapter.UpdateCommand = tempadapter.SelectCommand;
tempadapter.UpdateCommand.CommandText = string.Format(
“UPDATE Categories SET CategoryName=”{0}”,
Description=”{1}” WHERE CategoryID={2}”,
this.Category[1].Text, this.Category[2].Text,
this.Category[0].Text);
tempadapter.UpdateCommand.Connection =
tempadapter.SelectCommand.Connection;
tempadapter.UpdateCommand.Connection.Open();
tempadapter.UpdateCommand.ExecuteNonQuery();
tempadapter.UpdateCommand.Connection.Close();
}
catch( Exception Err )
{
MessageBox.Show( Err.Message );
}
}
}

private void Insert_Record( object objCtrl,
System.Data.DataRowCollection datarowcol,
System.Windows.Forms.TabControl tctrl,
System.Windows.Forms.TabPage tg,
System.Data.DataSet ds )
{
ListView lv = ( ( ListView )objCtrl );
// Creat new listview item
ListViewItem item = new ListViewItem();
// Retrieve total row in the table
int iRowCount = datarowcol.Count;
int iCount=0;

try
{
// Retrieve each textbox in the control array
foreach( Control ctrl in this.Category )
{
if( iCount == 0 ) // add data to first column of the list
{
item.Text = ctrl.Text;
datarowcol[iRowCount+1][iCount] = ctrl.Text;
}
else
{ // Add data to sub column
item.SubItems.Add( ctrl.Text );
datarowcol[iRowCount+1][iCount] = ctrl.Text;
}
// Increasement count
iCount++;
}
}
catch( Exception Err )
{
MessageBox.Show( Err.Message );
}

// Update Table
ds.Tables[tg.Name].AcceptChanges();
// Try to update database
try
{
// Retrieve OleDbDataAdapter
System.Data.OleDb.OleDbDataAdapter tempadapter =
( System.Data.OleDb.OleDbDataAdapter )tctrl.Tag;
//tempadapter.SelectCommand.CommandText =
//string.Format( “SELECT * FROM {0}”, tg.Name );

tempadapter.InsertCommand = tempadapter.SelectCommand;
tempadapter.InsertCommand.CommandText = string.Format(
“INSERT INTO Categories SET CategoryID={0}
CategoryName=”{1}”, Description=”{2}”,
Picture={3}”, this.Category[0].Text,
this.Category[1].Text, this.Category[2].Text,
this.pictureBox1.Image );
tempadapter.InsertCommand.Connection = tempadapter.
SelectCommand.
Connection;
tempadapter.InsertCommand.Connection.Open();
tempadapter.InsertCommand.ExecuteNonQuery();
tempadapter.InsertCommand.Connection.Close();
}
catch( Exception Err )
{
MessageBox.Show( Err.Message );
}
}
}
}

END OF PART TWO

Downloads

Download demo project – 2.07 Mb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read