pp/5/VoteForm.cs 2.2 KB (2300b); Sat, 04 Jun 2011 21:49
´╗┐using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Cselian.Voting
{
	public partial class VoteForm : Form
	{
		static VoteForm()
		{
			Candidate.CountChanged += new EventHandler(Candidate_CountChanged);
		}

		static void Candidate_CountChanged(object sender, EventArgs e)
		{
			Save();
		}

		private const string FileName = "Candidates.txt";
		private static List<ICandidate> Candidates = new List<ICandidate>();

		public VoteForm()
		{
			InitializeComponent();
			Reload();
		}

		private void Reload()
		{
			Candidates.Clear();
			VotesPanel.Controls.Clear();
			var names = File.ReadAllLines(FileName);
			foreach (var item in names)
			{
				if (string.IsNullOrEmpty(item)) continue;
				var nameCt = item.Split("=".ToCharArray(), 2);
				var ct = nameCt.Length == 1 ? 0 : int.Parse(nameCt[1]);
				var c = new Candidate(nameCt[0], ct);
				Candidates.Add(c);
				VotesPanel.Controls.Add(c);
			}
		}

		private static void Save()
		{
			Candidates.Sort(Candidate.Compare);
			var sb = new StringBuilder();
			foreach (var item in Candidates)
			{
				sb.AppendLine(item.PersonName + "=" + item.Votes);
			}
			var f = new FileInfo(FileName);

			if (f.Exists) 
			{
				if ((f.Attributes | FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
					f.Attributes = FileAttributes.Normal;
				f.Delete();
			}
			File.WriteAllText(FileName, sb.ToString());
		}

		private void TabCtl_Selected(object sender, TabControlEventArgs e)
		{
			if (TabCtl.SelectedTab != CountTab) return;
			Candidates.Sort(Candidate.Compare);
			var list = new List<string>();
			foreach (var item in Candidates) list.Add(item.ToString());
			ResultsCtl.DataSource = list;
		}

		private void BtnClear_Click(object sender, EventArgs e)
		{
			foreach (var item in Candidates)
			{
				item.Clear();
			}
			TabCtl_Selected(sender, null);
			Save();
		}

		private void BtnEditNames_Click(object sender, EventArgs e)
		{
			System.Diagnostics.Process.Start("notepad.exe", "\"" + new FileInfo(FileName).FullName + "\"");
		}

		private void BtnReload_Click(object sender, EventArgs e)
		{
			Reload();
			TabCtl_Selected(sender, null);
		}
	}
}