using System;
using System.Drawing.Design;
using System.ComponentModel.Design;
using System.Collections;

namespace Netlm.DataGridGost
{
	/// <summary>
	/// KeyValuePairEditor 的摘要说明。
	/// </summary>
	public class KeyValuePairCollectionEditor : CollectionEditor
	{
		public KeyValuePairCollectionEditor(Type type) : base(type){}
		private  KeyValuePair[] currentKvps = null;
		
		protected override System.Object CreateInstance(System.Type itemType)
		{
			if (itemType == typeof(KeyValuePair))
			{
				return (KeyValuePair)base.CreateInstance(itemType);
			}
            
			return base.CreateInstance(itemType);
		}
		
		protected override object SetItems(object editValue, object[] value)
		{
			try
			{
				currentKvps = null;
				currentKvps = new KeyValuePair[value.Length];
				for(int i=0;i<value.Length;i++)
				{
					currentKvps[i] = value[i] as KeyValuePair;
					currentKvps[i].KeyChanged +=new KeyValuePairKeyChanged(KeyValuePairCollectionEditor_KeyChanged);
				}
				return base.SetItems (editValue, value);
			}
			catch (Exception ex)
			{
				return null;
			}
		}

		private void KeyValuePairCollectionEditor_KeyChanged(string keystr)
		{
			for(int i=0; i<currentKvps.Length;i++)
			{
				for(int j =i+1;j<currentKvps.Length;j++)
				{
					if(currentKvps[i].Key.Trim()==currentKvps[j].Key.Trim())
						throw new ArgumentException(currentKvps[i].Key+"已存在");
				}
			}
		}
	}
}
