Dear all,
Below is my first C# program. Please be gentle with me. I
was asked to
produce a simple Windows Forms program to save Key/Value
pairs, along
with the a couple of sorting choices.
Although I have done many years of C++, my latest job
entails plenty of
C#, so I need to get upto speed quickly.
I am sorry if any of this is Off Topic, or breaks any
etiquette.
So, here it is. I am probably breaking many rules or
conventions but I
though that having a crack at it myself first would be the
done thing.
Any comments or suggestions, are greatly appreciated. I
welcome your
expert opinions and advice.
Thanks
Nick
-- Form1.cs Start --
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text.RegularExpressions;
using System.Xml;
namespace KeyValue
{
public enum SortOn { Name, Value };
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox
NameValue;
private System.Windows.Forms.Button Add;
private System.Windows.Forms.Button Delete;
private System.Windows.Forms.Button
SaveAsXML;
private System.Windows.Forms.Button Exit;
private System.Windows.Forms.ListBox NameValueList;
private System.Windows.Forms.RadioButton
radioSortByName;
private System.Windows.Forms.RadioButton
radioSortByValue;
private System.Windows.Forms.Label ListTitle;
private int nSelectedIndex = -1;
private SortOn sorton = SortOn.Name;
private string[] SortText = new string[]
{"Name", "Value"};
private System.Collections.SortedList KeyValues = new
System.Collections.SortedList();
private bool IsChanged = false;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container
components =
null;
public Form1()
{
//
// Required for Windows Form
Designer support
//
InitializeComponent();
DoSort();
}
/// <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.label1 = new System.Windows.Forms.Label();
this.NameValue = new System.Windows.Forms.TextBox();
this.Add = new System.Windows.Forms.Button();
this.ListTitle = new System.Windows.Forms.Label();
this.Delete = new System.Windows.Forms.Button();
this.SaveAsXML = new System.Windows.Forms.Button();
this.Exit = new System.Windows.Forms.Button();
this.NameValueList = new
System.Windows.Forms.ListBox();
this.radioSortByName = new
System.Windows.Forms.RadioButton();
this.radioSortByValue = new
System.Windows.Forms.RadioButton();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(16,
8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(240, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Name / Value Pair";
//
// NameValue
//
this.NameValue.Location = new System.Drawing.Point(16,
24);
this.NameValue.Name = "NameValue";
this.NameValue.Size = new System.Drawing.Size(240,
20);
this.NameValue.TabIndex = 1;
this.NameValue.Text = "Name=Value";
//
// Add
//
this.Add.Location = new System.Drawing.Point(280, 24);
this.Add.Name = "Add";
this.Add.Size = new System.Drawing.Size(104, 23);
this.Add.TabIndex = 2;
this.Add.Text = "&Add";
this.Add.Click += new
System.EventHandler(this.Add_Click);
//
// ListTitle
//
this.ListTitle.Location = new System.Drawing.Point(16,
64);
this.ListTitle.Name = "ListTitle";
this.ListTitle.Size = new System.Drawing.Size(240,
16);
this.ListTitle.TabIndex = 4;
this.ListTitle.Text = "Name / Value Pair
List";
//
// Delete
//
this.Delete.Location = new System.Drawing.Point(280,
176);
this.Delete.Name = "Delete";
this.Delete.Size = new System.Drawing.Size(104, 23);
this.Delete.TabIndex = 7;
this.Delete.Text = "&Delete";
this.Delete.Click += new
System.EventHandler(this.Delete_Click);
//
// SaveAsXML
//
this.SaveAsXML.Location = new
System.Drawing.Point(280, 240);
this.SaveAsXML.Name = "SaveAsXML";
this.SaveAsXML.Size = new System.Drawing.Size(104,
23);
this.SaveAsXML.TabIndex = 8;
this.SaveAsXML.Text = "&Save as XML";
this.SaveAsXML.Click += new
System.EventHandler(this.SaveAsXML_Click);
//
// Exit
//
this.Exit.Location = new System.Drawing.Point(280,
296);
this.Exit.Name = "Exit";
this.Exit.Size = new System.Drawing.Size(104, 23);
this.Exit.TabIndex = 9;
this.Exit.Text = "E&xit";
this.Exit.Click += new
System.EventHandler(this.Exit_Click);
//
// NameValueList
//
this.NameValueList.Location = new
System.Drawing.Point(16, 88);
this.NameValueList.Name = "NameValueList";
this.NameValueList.Size = new System.Drawing.Size(240,
225);
this.NameValueList.TabIndex = 10;
this.NameValueList.SelectedIndexChanged += new
System.EventHandler(this.NameValueList_SelectedIndexChanged_
1);
//
// radioSortByName
//
this.radioSortByName.Checked = true;
this.radioSortByName.Location = new
System.Drawing.Point(280,
88);
this.radioSortByName.Name =
"radioSortByName";
this.radioSortByName.TabIndex = 11;
this.radioSortByName.TabStop = true;
this.radioSortByName.Text = "Sort By
&Name";
this.radioSortByName.Click += new
System.EventHandler(this.radioSortByName_Click);
//
// radioSortByValue
//
this.radioSortByValue.Location = new
System.Drawing.Point(280,
120);
this.radioSortByValue.Name =
"radioSortByValue";
this.radioSortByValue.TabIndex = 12;
this.radioSortByValue.Text = "Sort By
&Value";
this.radioSortByValue.Click += new
System.EventHandler(this.radioSortByValue_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
13);
this.ClientSize = new System.Drawing.Size(408, 326);
this.Controls.Add(this.radioSortByValue);
this.Controls.Add(this.radioSortByName);
this.Controls.Add(this.NameValueList);
this.Controls.Add(this.Exit);
this.Controls.Add(this.SaveAsXML);
this.Controls.Add(this.Delete);
this.Controls.Add(this.ListTitle);
this.Controls.Add(this.Add);
this.Controls.Add(this.NameValue);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Key-Value Pair Entry Program";
this.Closing += new
System.ComponentModel.CancelEventHandler(this.Form1_Closing)
;
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the
application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Exit_Click(object sender, System.EventArgs
e)
{
this.Close();
}
private bool DoExit()
{
if (IsChanged)
{
string ErrStr = "You have not saved your
changes!nDo you want
to save them now? ";
MessageBoxButtons buttons =
MessageBoxButtons.YesNoCancel;
DialogResult result = MessageBox.Show(this, ErrStr,
"Key-Value
Exit", buttons,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1);
switch (result)
{
case DialogResult.Yes :
SaveAsXML_Click(null, null);
if (IsChanged) return false;
break;
case DialogResult.No :
return true;
break;
default :
return false;
break;
}
}
return true;
}
private void Add_Click(object sender,
System.EventArgs
e)
{
bool IsOk = true;
string ErrStr = "";
if (this.NameValue.Text != "")
{
// Validate the input.
string[] Tokens = this.NameValue.Text.Split(new
char[] {'='});
if (Tokens.Length != 2)
{
IsOk = false;
ErrStr += "There should be two
tokens.n";
}
else
{
for (int i = 0; i < Tokens.Length; i++)
{
if (Tokens[i].Length == 0)
{
IsOk = false;
ErrStr += "Syntax Error: " + ((i ==
0) ? "Name" :
"Value") + " portion is blank!n";
}
else
{
// Use a regular expression to allow
alphanumerics and
space chars only.
Regex objAlphaNumericPattern = new
Regex("[^a-zA-Z0-9
]");
if (objAlphaNumericPattern.IsMatch(Tokens[i]))
{
IsOk = false;
ErrStr += "'" + Tokens[i] +
"' should be alpha numerics
only.n";
}
}
}
}
if (IsOk)
{
// Now check for duplicates.
if (KeyValues.ContainsKey(Tokens[0]))
{
// Have a duplicate.
IsOk = false;
ErrStr += "'" + Tokens[0] + "' is
a duplicate.n";
NameValueList.SelectedIndex =
KeyValues.IndexOfKey(Tokens[0]);
}
else
{
// All OK, Insert the key-value pair.
DoInsert(Tokens[0], Tokens[1]);
this.NameValue.Text = "";
}
}
}
else
{
IsOk = false;
ErrStr = "Key Value pair is blank!";
}
if (!IsOk)
{
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(this, ErrStr,
"Key-Value
Validation", buttons,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1);
this.NameValue.Focus();
}
}
private void SortByName_Click(object sender,
System.EventArgs e)
{
this.sorton = SortOn.Name;
DoSort();
}
private void SortByValue_Click(object sender,
System.EventArgs e)
{
this.sorton = SortOn.Value;
DoSort();
}
private void DoSort()
{
ArrayList list = new ArrayList();
this.ListTitle.Text = "Name / Value Pair ( Sorted
By " +
SortText[(int)this.sorton] + " )";
// Empty the screen list and prepare to refill.
this.NameValueList.Items.Clear();
this.NameValueList.BeginUpdate();
foreach(string Name in KeyValues.Keys)
{
Organizer o = new Organizer(Name,
(object)KeyValues[Name]);
o.SortOn = this.sorton;
list.Add(o);
}
// Now sort the list.
list.Sort();
foreach(Organizer o in list)
{
this.NameValueList.Items.Add(o.Key + "=" +
o.Value);
}
this.NameValueList.EndUpdate();
}
private void DoInsert(string TheName, string TheValue)
{
KeyValues.Add(TheName, TheValue);
DoSort();
IsChanged = true;
this.Text = "Key-Value Pair Entry Program "
+ (IsChanged ? "*" :
" ");
}
private void Delete_Click(object sender,
System.EventArgs e)
{
string ErrStr = "";
nSelectedIndex = this.NameValueList.SelectedIndex;
if (nSelectedIndex >= 0 && nSelectedIndex
<
this.NameValueList.Items.Count)
{
ErrStr = "Are you sure you want to delete the
Key-Value Pair '"
+
(string)this.NameValueList.SelectedItem +
"'?";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result = MessageBox.Show(this, ErrStr,
"Key-Value
Delete?", buttons,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1);
if (result == DialogResult.Yes)
{
// remove the Key from the KeyValues List.
string[] TheNameValuePair =
this.NameValueList.SelectedItem.ToString().Split(new char[]
{'='});
KeyValues.RemoveAt(KeyValues.IndexOfKey(TheNameValuePair[0])
);
this.NameValue.Text = "";
DoSort();
IsChanged = true;
this.Text = "Key-Value Pair Entry Program
" + (IsChanged ?
"*" : " ");
}
}
}
private void SaveAsXML_Click(object sender,
System.EventArgs e)
{
SaveFileDialog fdlg = new SaveFileDialog();
fdlg.Title = "Save As" ;
fdlg.InitialDirectory = "c:" ;
fdlg.Filter = "All files (*.*)|*.*|Xml files
(*.xml)|*.xml" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
XmlTextWriter myXmlTextWriter = new XmlTextWriter
(fdlg.FileName, null);
myXmlTextWriter.Formatting =
System.Xml.Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteDocType("Key-Value",
null, null, null);
myXmlTextWriter.WriteComment("This file holds
Key-Value
pairs");
myXmlTextWriter.WriteStartElement("Key-Values");
foreach(string Name in KeyValues.Keys)
{
myXmlTextWriter.WriteStartElement("Item", null);
myXmlTextWriter.WriteAttributeString("Key", Name);
myXmlTextWriter.WriteAttributeString("Value",
KeyValues[Name].ToString());
myXmlTextWriter.WriteEndElement();
}
myXmlTextWriter.WriteEndElement();
//Write the XML to file and close the
myXmlTextWriter
myXmlTextWriter.Flush();
myXmlTextWriter.Close();
IsChanged = false;
this.Text = "Key-Value Pair Entry Program
" + (IsChanged ? "*"
: " ");
}
}
private void NameValueList_SelectedIndexChanged_1(object
sender,
System.EventArgs e)
{
nSelectedIndex = this.NameValueList.SelectedIndex;
string szSelected =
(string)this.NameValueList.SelectedItem;
this.NameValue.Text = szSelected;
}
private void radioSortByName_Click(object sender,
System.EventArgs
e)
{
this.sorton = SortOn.Name;
DoSort();
}
private void radioSortByValue_Click(object sender,
System.EventArgs
e)
{
this.sorton = SortOn.Value;
DoSort();
}
private void Form1_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
if (!DoExit())
{
e.Cancel = true;
}
}
}
}
-- Form1.cs End --
-- Organizer.cs Start --
using System;
namespace KeyValue
{
/// <summary>
/// Summary description for Organizer
/// </summary>
public class Organizer : IComparable
{
string _key;
object _value;
SortOn _sortOn = SortOn.Value;
public SortOn SortOn { get { return _sortOn; }
set { _sortOn
= value; } }
public object Value { get { return _value; }
set { _value
= value; } }
public string Key { get { return _key; }
set { _key =
value; } }
public Organizer(string key, object thevalue)
{
_key = key;
_value = thevalue;
}
#region IComparable Members
public int CompareTo(object obj)
{
int result = 0;
if(_sortOn == SortOn.Value)
{
if(obj != null)
{
result = _value.ToString().CompareTo(((Organizer)
obj).Value.ToString());
}
}
else
{
result = _key.CompareTo(((Organizer) obj).Key);
}
return result;
}
#endregion
}
}
-- Organizer.cs End --
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the
Google Groups "C-Sharp (C#)" group.
To post to this group, send email to C_Sharp googlegroups.com
To unsubscribe from this group, send email to
C_Sharp-unsubscribe googlegroups.com
For more options, visit this group at http://groups.
google.com/group/C_Sharp
-~----------~----~----~----~------~----~------~--~---
|