public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			/*
			PropertyDescriptor member = TypeDescriptor.GetProperties(context.Instance)["ItemBindings"];
			System.Web.UI.Design.ControlDesigner.InvokeTransactedChange((Component)context.Instance, new TransactedChangeCallback(this.InnerEditValues), null, null, member);
			*/

			DataBindingControl control = (DataBindingControl)context.Instance;
			DataBindingItemCollection bindings = (DataBindingItemCollection)control.ItemBindings;
			DataBindingItem binding = new DataBindingItem();

			binding.ControlID = "Shen Zheng";
			bindings.Add(binding);
			
			context.OnComponentChanged();
			return bindings;
		}
        /// <summary>
        /// Add a DataBindingItem to the collection
        /// </summary>
        /// <param name="Item"></param>
        public void Add(DataBindingItem Item)
        {
           if (_ParentDataBinder != null)
            {
                Item.Page = _ParentDataBinder.Page;
                Item.Binder = _ParentDataBinder;

                // VS Designer adds new items as soon as their accessed
                // but items may not be valid so we have to clean up
                if (_ParentDataBinder.DesignMode)
                {
                   // Remove any blank items
                   UpdateListInDesignMode();
                }
            }

            InnerList.Add(Item);
        }
		public void CopyFromBindingItem(DataBindingItem item)
		{
			ExceptionHelper.FalseThrow<ArgumentNullException>(item != null, "item");

			this.ControlID = item.ControlID;
			this.ControlPropertyName = item.ControlPropertyName;
			this.ClientIsHtmlElement = item.ClientIsHtmlElement;
			this.ClientDataPropertyName = item.ClientDataPropertyName;
			this.ClientPropName = item.ClientPropName;
			this.ClientSetPropName = item.ClientSetPropName;
			this.ClientDataType = item.ClientDataType;
			this.IsValidate = item.IsValidate;
			this.IsValidateOnBlur = item.IsValidateOnBlur;
			this.DataPropertyName = item.DataPropertyName;
			this.Direction = item.Direction;
			this.Format = item.Format;
			this.EnumAutoBinding = item.EnumAutoBinding;
			this.ItemTrimBlankType = item.ItemTrimBlankType;
			this.EnumUsage = item.EnumUsage;
			this.ValidationGroup = item.ValidationGroup;
			this.AutoFormatOnBlur = item.AutoFormatOnBlur;
		}
        /// <summary>
        /// 设置与控件进行绑定的数据成员
        /// </summary>
        /// <param name="control">需要进行绑定的控件</param>
        /// <param name="dataMember">数据成员</param>
        public void SetDataMember(Control control, string dataMember)
        {
            var dataBindingItem = dataBindingItems.FirstOrDefault(item => item.Control == control);

            if (string.IsNullOrEmpty(dataMember))
            {
                if (dataBindingItem != null)
                {
                    dataBindingItems.Remove(dataBindingItem);
                }
            }
            else
            {
                if (dataBindingItem == null)
                {
                    dataBindingItem         = new DataBindingItem();
                    dataBindingItem.Control = control;

                    dataBindingItems.Add(dataBindingItem);
                }

                dataBindingItem.DataMember = dataMember;
            }
        }
		/// <summary>
		/// 获取单个对象属性
		/// </summary>
		/// <param name="dataPropertyInfo">属性</param>
		/// <param name="currData">当前数据</param>
		/// <param name="dataTargetProName">目标属性名称</param>
		/// <param name="item">绑定项</param>
		private void MappingOneControlToOneData(object currData, string dataTargetProName, DataBindingItem item)
		{
			Control targetControl = FindControlByPath(this, item.ControlID);

			//控件对象路径
			string targetPro = string.Empty;
			//控件对象属性
			string targetProName = item.ControlPropertyName;
			ExceptionHelper.FalseThrow(targetControl != null, "不能找到ID为{0}的控件", item.ControlID);

			SplitPath(targetControl, item.ControlPropertyName, out targetPro, out targetProName);

			Type dataType = this.DataType;

			if (currData != null)
				dataType = currData.GetType();

			//获取目标属性值
			object targetItem = FindObjectByPath(targetControl, targetPro);
			if (targetItem != null && dataType != null)
			{
				PropertyInfo piDest = TypePropertiesCacheQueue.Instance.GetPropertyInfo(dataType,
						GetObjectPropertyName(dataType, dataTargetProName));

				if (piDest != null)
				{
					if (targetItem is CheckBoxList && piDest.PropertyType.IsEnum && FlagsAttribute.IsDefined(piDest.PropertyType, typeof(FlagsAttribute)))
					{
						//Flags型的枚举和CheckBox之间的特殊处理
						CollectDataFromCheckBoxListToFlagsEnumProperty(item, ((ListControl)targetItem).Items, piDest, currData);
					}
					else
					{
						//获取绑定属性上的信息,绑定对象属性
						object targetValue = FindObjectByPath(targetItem, targetProName);

						if (piDest.CanWrite)
						{
							targetValue = UnformatControlProperty(targetValue, piDest, item);

							SetSimpleValueToData(item, piDest, currData, targetValue);
						}
						else
						{
							ProcessCollectionProperty(piDest, currData, targetValue);
						}
					}
				}
			}
		}
		/// <summary>
		/// 将枚举数据绑定至列表型控件
		/// </summary>
		/// <param name="enumType">枚举类型</param>
		/// <param name="data">当前数据</param>
		/// <param name="ddl">下拉控件</param>
		/// <param name="item">绑定数据</param>
		private void BindEnumToListControl(System.Type enumType, object data, ListControl lControl, DataBindingItem item)
		{
			if (item.EnumAutoBinding)
			{
				EnumItemDescriptionList listEnum = EnumItemDescriptionAttribute.GetDescriptionList(enumType);

				List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();

				foreach (EnumItemDescription enumItem in listEnum)
				{
					KeyValuePair<int, string> kp = new KeyValuePair<int, string>(enumItem.EnumValue,
						string.IsNullOrEmpty(enumItem.Description) ? enumItem.Name : enumItem.Description);

					list.Add(kp);
				}

				lControl.DataSource = BuildEnumList(enumType, item.EnumUsage);

				lControl.DataValueField = "Key";
				lControl.DataTextField = "Value";
				lControl.DataBind();
			}

			int intData = Convert.ToInt32(data);

			if ((lControl is CheckBoxList) && FlagsAttribute.IsDefined(enumType, typeof(FlagsAttribute)))
			{
				foreach (ListItem lItem in lControl.Items)
				{
					int v = int.Parse(lItem.Value);

					if ((v & intData) != 0)
						lItem.Selected = true;
				}
			}
			else
			{
				string strValue = intData.ToString();

				foreach (ListItem lItem in lControl.Items)
				{
					if (lItem.Value == strValue)
					{
						lControl.SelectedValue = strValue;
						break;
					}
				}
			}
		}
		/// <summary>
		/// 将枚举数据绑定至文本型控件
		/// </summary>
		/// <param name="enumType">枚举类型</param>
		/// <param name="data">当前数据</param>
		/// <param name="lab">控件</param>
		/// <param name="item">绑定数据</param>
		private void BindEnumToTextControl(object data, ITextControl tContrl, DataBindingItem item)
		{
			if (item.EnumAutoBinding)
			{
				string description = EnumItemDescriptionAttribute.GetDescription((Enum)data);

				string defaultDataValue = string.Empty;

				switch (item.EnumUsage)
				{
					case EnumUsageTypes.UseEnumValue:
						defaultDataValue = ((int)data).ToString();
						break;
					case EnumUsageTypes.UseEnumString:
						defaultDataValue = data.ToString();
						break;
				}

				tContrl.Text = string.IsNullOrEmpty(description) ? defaultDataValue : description;
			}
		}
        /// <summary>
        /// Returns a UserField name. Returns UserFieldname if set, or if not
        /// attempts to derive the name based on the field.
        /// </summary>
        /// <param name="Control"></param>
        /// <returns></returns>
        protected string DeriveUserFieldName(DataBindingItem Item)
        {
            if (!string.IsNullOrEmpty(Item.UserFieldName))
                return Item.UserFieldName;

            string ControlID = Item.ControlInstance.ID;

            // Try to get a name by stripping of control prefixes
            string ControlName = Regex.Replace(Item.ControlInstance.ID, "^txt|^chk|^lst|^rad|", "", RegexOptions.IgnoreCase);
            if (ControlName != ControlID)
                return ControlName;

            // Nope - use the default ID
            return ControlID;
        }
		/// <summary>
		/// 检测DataBingdingData
		/// </summary>
		/// <param name="item"></param>
		/// <param name="control"></param>
		/// <returns></returns>
		private bool CheckDataBingdingItem(DataBindingItem item, Control control)
		{
			if (control == null)
				return false;//查找不到控件跳过

			if (control is WebControl)
			{
				if (!((WebControl)control).Enabled) return false;//如果控件无效跳过
			}

			PropertyInfo propertyinfo = TypePropertiesCacheQueue.Instance.GetPropertyInfoDirectly(control.GetType(), "ReadOnly");

			if (propertyinfo == null)
				return true;//如果控件没有ReadOnly属性返回验证

			if (((bool)propertyinfo.GetValue(control, null)))
				return false; //如果控件只读,跳过。

			if (!item.IsValidate)
				return false;//不校验跳过

			return true;
		}
        /// <summary>
        /// Fires the BeforeUnbindControl event
        /// </summary>
        /// <param name="Item"></param>
        /// <returns></returns>
        public bool OnBeforeUnbindControl(DataBindingItem Item)
        {            
            if (BeforeUnbindControl != null)
                return BeforeUnbindControl(Item);

            return true;
        }
        protected void btn_getEntityDefine_Click(object sender, EventArgs e)
        {
            center_panel.Visible = true;



            RecordResultCollection rrc = GetData(txt_Code.Text.Trim());

            List <string> cou = rrc.Select(p => p.EntityName).Distinct().ToList();

            foreach (string entityName in cou)
            {
                ClientGrid gr = new ClientGrid();

                gr.EnableViewState = false;


                gr.ID                 = entityName;
                gr.AllowPaging        = false;
                gr.ShowEditBar        = true;
                gr.AutoPaging         = false;
                gr.ShowCheckBoxColumn = true;
                gr.ID                 = Guid.NewGuid().ToString();
                controlIDs.Add(gr.ID);
                var recordCollention = rrc.Where(p => p.EntityName.Equals(entityName));
                ClientGridColumn cgc = new ClientGridColumn();  //checkbox
                cgc.SelectColumn  = true;
                cgc.ShowSelectAll = true;
                cgc.HeaderStyle   = "{width:'30px',textAlign:'left',fontWeight:'bold'}";
                cgc.ItemStyle     = "{width:'30px',textAlign:'left'}";

                gr.Columns.Add(cgc);

                ClientGridColumn cgIndex = new ClientGridColumn();

                cgIndex.DataField   = "rowIndex";
                cgIndex.HeaderText  = "序号";
                cgIndex.HeaderStyle = "{width:'30px',textAlign:'center'}";
                cgIndex.ItemStyle   = "{width:'30px',textAlign:'center'}";
                cgIndex.DataType    = DataType.Integer;
                gr.Columns.Add(cgIndex);

                ClientGridColumn cgFieldName = new ClientGridColumn();
                cgFieldName.DataField             = "FieldName";
                cgFieldName.HeaderText            = "字段名";
                cgFieldName.HeaderStyle           = "{textAlign:'left'}";
                cgFieldName.ItemStyle             = "{textAlign:'left'}";
                cgFieldName.DataType              = DataType.String;
                cgFieldName.EditTemplate.EditMode = ClientGridColumnEditMode.TextBox;
                gr.Columns.Add(cgFieldName);

                ClientGridColumn cgFieldDesc = new ClientGridColumn();
                cgFieldDesc.DataField             = "FieldDesc";
                cgFieldDesc.HeaderText            = "字段描述";
                cgFieldDesc.HeaderStyle           = "{textAlign:'left'}";
                cgFieldDesc.ItemStyle             = "{textAlign:'left'}";
                cgFieldDesc.DataType              = DataType.String;
                cgFieldDesc.EditTemplate.EditMode = ClientGridColumnEditMode.TextBox;
                gr.Columns.Add(cgFieldDesc);

                ClientGridColumn cgFieldTypeName = new ClientGridColumn();
                cgFieldTypeName.DataField             = "FieldType";
                cgFieldTypeName.HeaderText            = "字段类型";
                cgFieldTypeName.HeaderStyle           = "{textAlign:'left'}";
                cgFieldTypeName.ItemStyle             = "{textAlign:'left'}";
                cgFieldTypeName.DataType              = DataType.String;
                cgFieldTypeName.EditTemplate.EditMode = ClientGridColumnEditMode.TextBox;
                gr.Columns.Add(cgFieldTypeName);


                ClientGridColumn cgFieldLength = new ClientGridColumn();
                cgFieldLength.DataField             = "FieldLength";
                cgFieldLength.HeaderText            = "字段长度";
                cgFieldLength.HeaderStyle           = "{textAlign:'left'}";
                cgFieldLength.ItemStyle             = "{textAlign:'left'}";
                cgFieldLength.DataType              = DataType.String;
                cgFieldLength.EditTemplate.EditMode = ClientGridColumnEditMode.TextBox;
                gr.Columns.Add(cgFieldLength);

                ClientGridColumn cgFieldDefaultValue = new ClientGridColumn();
                cgFieldDefaultValue.DataField             = "DefaultValue";
                cgFieldDefaultValue.HeaderText            = "字段默认值";
                cgFieldDefaultValue.HeaderStyle           = "{textAlign:'left'}";
                cgFieldDefaultValue.ItemStyle             = "{textAlign:'left'}";
                cgFieldDefaultValue.DataType              = DataType.String;
                cgFieldDefaultValue.EditTemplate.EditMode = ClientGridColumnEditMode.TextBox;
                gr.Columns.Add(cgFieldDefaultValue);

                ClientGridColumn cgOuterFieldName = new ClientGridColumn();
                cgOuterFieldName.DataField   = "FieldName";
                cgOuterFieldName.HeaderText  = "关联字段/结构";
                cgOuterFieldName.HeaderStyle = "{textAlign:'left'}";
                cgOuterFieldName.ItemStyle   = "{textAlign:'left'}";
                cgOuterFieldName.DataType    = DataType.String;
                gr.Columns.Add(cgOuterFieldName);
                gr.InitialData = recordCollention.ToList();



                DataBindingItem dbItem = new DataBindingItem();
                dbItem.ControlID           = entityName;
                dbItem.DataPropertyName    = "EntityFieldMappingCollection";
                dbItem.ControlPropertyName = "InitialData";
                dbItem.Direction           = BindingDirection.Both;

                Panel pa = new Panel();

                Label lb = new Label();
                lb.Text = string.Format(@"<div class='dialogTitle'>
                                <div class='lefttitle' style='text-align: left;'>
                                    <img src='../Images/icon_01.gif'/>
                                    编辑{0}主实体字段及关联</div>
                            </div>", entityName);
                pa.Controls.Add(lb);

                Panel pn = new Panel();
                pn.ID       = "Panel_" + entityName;
                pn.CssClass = "dialogContent";

                pn.Controls.Add(gr);

                center_panel.Controls.Add(pa);
                center_panel.Controls.Add(pn);
            }



            ViewState["controlids"] = controlIDs;



            EntityMapping mapping = new EntityMapping();
        }
		/// <summary>
		/// 反向格式化数据
		/// </summary>
		/// <param name="sourceData">数据源</param>
		/// <param name="piDest">属性</param>
		/// <param name="item">绑定项</param>
		/// <returns></returns>
		private object UnformatControlProperty(object sourceData, PropertyInfo piDest, DataBindingItem item)
		{
			object targetValue = sourceData;

			if (ControlDataIsNull(sourceData))
			{
				if (piDest.PropertyType.IsValueType)
					targetValue = TypeCreator.CreateInstance(piDest.PropertyType);
			}
			else
			{
				if (IsNumericType(piDest.PropertyType))
				{
					if (sourceData.GetType() == typeof(string))
						sourceData = ((string)sourceData).Replace(",", string.Empty);
				}

				targetValue = DataConverter.ChangeType(sourceData, GetRealDataType(piDest.PropertyType));

				if (piDest.PropertyType == typeof(string))
				{
					switch (item.ItemTrimBlankType)
					{
						case TrimBlankType.Right:
							{
								targetValue = targetValue.ToString().TrimEnd(new char[] { ' ' });
								break;
							}
						case TrimBlankType.Left:
							{
								targetValue = targetValue.ToString().TrimStart(new char[] { ' ' });
								break;
							}
						case TrimBlankType.None:
							{
								break;
							}
						case TrimBlankType.ALL:
							{
								targetValue = new Regex(@"\s").Replace(targetValue.ToString(), "");
								break;
							}
						default:
							{
								targetValue = targetValue.ToString().Trim();
								break;
							}
					}

				}
			}

			return targetValue;
		}
		/// <summary>
		/// 格式化数据
		/// </summary>
		/// <param name="sourceData">数据源</param>
		/// <param name="piDest">属性</param>
		/// <param name="item">绑定项</param>
		/// <returns></returns>
		private object FormatDataProperty(object sourceData, PropertyInfo piDest, DataBindingItem item)
		{
			object targetValue = null;

			if (sourceData == null)
				return string.Empty;

			if (sourceData.GetType().IsEnum && item.EnumUsage == EnumUsageTypes.UseEnumValue)
			{
				targetValue = DataConverter.ChangeType((int)sourceData, GetRealDataType(piDest.PropertyType));
			}
			else
			{
				if (string.IsNullOrEmpty(item.Format))
					targetValue = DataConverter.ChangeType(sourceData, GetRealDataType(piDest.PropertyType));
				else
					targetValue = sourceData;
			}

			if (piDest.PropertyType == typeof(string))
			{
				bool isDefault = false;

				if (item.FormatDefaultValueToEmpty)
				{
					Type srcDataType = sourceData.GetType();

					if (srcDataType.IsValueType && srcDataType != typeof(Boolean))
					{
						object defaultValue = TypeCreator.CreateInstance(srcDataType);

						if (sourceData.Equals(defaultValue) && string.IsNullOrEmpty(item.Format))
						{
							targetValue = string.Empty;
							isDefault = true;
						}
					}
				}

				//除掉else,只要是设置了格式化,就应该格式化数据。 
				if (!isDefault && string.IsNullOrEmpty(item.Format) == false)
					targetValue = string.Format(item.Format, sourceData);
			}

			return targetValue;
		}
        /// <summary>
        /// This method only adds a data binding item, but doesn't bind it to anything.
        ///  This can be useful for only displaying errors
        /// <seealso>Class DataBinder</seealso>
        /// </summary>
        /// <param name="ControlToBind">
        /// An instance of the control to bind to
        /// </param>
        public DataBindingItem AddBinding(Control ControlToBind)
        {
            DataBindingItem Item = new DataBindingItem(this);

            Item.ControlInstance = ControlToBind;
            Item.ControlId = ControlToBind.ID;
            Item.Page = Page;

            DataBindingItems.Add(Item);

            return Item;
        }
        /// <summary>
        /// Adds a binding error for DataBindingItem control. This is the most efficient
        /// way to add a BindingError. The other overloads call into this method after
        /// looking up the Control in the DataBinder.
        /// </summary>
        /// <param name="ErrorMessage"></param>
        /// <param name="BindingItem"></param>
        /// <returns></returns>
        public bool AddBindingError(string ErrorMessage, DataBindingItem BindingItem)
        {

            // Associated control found - add icon and link id
            if (BindingItem.ControlInstance != null)
                BindingErrors.Add(new BindingError(ErrorMessage, BindingItem.ControlInstance.ClientID));
            else
            {
                // Just set the error message
                BindingErrors.Add(new BindingError(ErrorMessage));
                return false;
            }

            BindingItem.BindingErrorMessage = ErrorMessage;

            // Insert the error text/icon as a literal
            if (ShowBindingErrorsOnControls && BindingItem.ControlInstance != null)
            {
                // Retrieve the Html Markup for the error
                // NOTE: If script code injection is enabled this is done with client
                //       script code to avoid Controls.Add() functionality which may not
                //       always work reliably if <%= %> tags are in document. Script HTML injection
                //       is the preferred behavior as it should work on any page. If script is used
                //       the message returned is blank and the startup script is embedded instead
                string HtmlMarkup = GetBindingErrorMessageHtml(BindingItem);

                if (!string.IsNullOrEmpty(HtmlMarkup))
                {
                    LiteralControl Literal = new LiteralControl();
                    Control Parent = BindingItem.ControlInstance.Parent;

                    int CtlIdx = Parent.Controls.IndexOf(BindingItem.ControlInstance);
                    try
                    {
                        // Can't add controls to the Control collection if <%= %> tags are on the page
                        Parent.Controls.AddAt(CtlIdx + 1, Literal);
                    }
                    catch { ; }
                }
            }

            return true;
        }
        /// <summary>
        /// Adds a binding to the control. This method is a simple way to establish a 
        /// binding.
        /// 
        /// Returns the Item so you can customize properties further
        /// <seealso>Class DataBinder</seealso>
        /// </summary>
        /// <param name="ControlToBind">
        /// An instance of a control that is to be bound
        /// </param>
        /// <param name="ControlPropertyToBind">
        /// The property on the control to bind to
        /// </param>
        /// <param name="SourceObjectNameToBindTo">
        /// The name of a data item or object to bind to.
        /// </param>
        /// <param name="SourceMemberToBindTo">
        /// The name of the property on the object to bind to
        /// </param>
        public DataBindingItem AddBinding(Control ControlToBind, string ControlPropertyToBind,
                          string SourceObjectNameToBindTo, string SourceMemberToBindTo)
        {
            DataBindingItem Item = new DataBindingItem(this);

            Item.ControlInstance = ControlToBind;
            Item.ControlId = ControlToBind.ID;
            Item.Page = Page;
            Item.BindingSource = SourceObjectNameToBindTo;
            Item.BindingSourceMember = SourceMemberToBindTo;

            DataBindingItems.Add(Item);

            return Item;
        }
        /// <summary>
        /// Manages errors that occur during unbinding. Sets BindingErrors collection and
        /// and writes out validation error display to the page if specified
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="ex"></param>
        private void HandleUnbindingError(DataBindingItem Item, Exception ex)
        {
            Item.IsBindingError = true;
            string DerivedUserFieldName = string.Empty;

            // Display Error info by setting BindingErrorMessage property
            try
            {
                string ErrorMessage = null;
                DerivedUserFieldName = string.Empty;    
                
                
                // Must check that the control exists - if invalid ID was
                // passed there may not be an instance!
                if (Item.ControlInstance == null)
                    ErrorMessage = Resources.InvalidControl + ": " + Item.ControlId;
                else
                {
                    DerivedUserFieldName = DeriveUserFieldName(Item);                    
                    if (ex is RequiredFieldException)
                    {
                        ErrorMessage = string.Format(this.IsRequiredErrorMessage, DerivedUserFieldName);
                    }
                    else if (ex is ValidationErrorException)
                    {
                        /// Binding Error Message will be set
                        ErrorMessage = ex.Message;
                    }
                    // Explicit error message returned
                    else if (ex is BindingErrorException)
                    {
                        ErrorMessage = ex.Message + " (" + DerivedUserFieldName + ")";
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(Item.BindingErrorMessage))
                            ErrorMessage = string.Format(this.UnBindingErrorMessage, DerivedUserFieldName);
                        else
                            // Control has a pre-assigned error message
                            ErrorMessage = Item.BindingErrorMessage;
                    }
                }
                AddBindingError(ErrorMessage, Item);
            }
            catch (Exception)
            {
                AddBindingError(string.Format(this.BindingErrorMessage,DerivedUserFieldName), Item);
            }
        }
        /// <summary>
        /// Returns a specific DataBinding Item for a given control.
        /// Always returns an item even if the Control is not found.
        /// If you need to check whether this is a valid item check
        /// the BindingSource property for being blank.
        /// 
        /// Extender Property Get method
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public DataBindingItem GetDataBindingItem(Control control)
        {
            foreach (DataBindingItem Item in DataBindingItems)
            {
                if (Item.ControlId == control.ID)
                {
                    // Ensure the binder is set on the item
                    Item.Binder = this;
                    return Item;
                }
            }

            DataBindingItem NewItem = new DataBindingItem(this);
            NewItem.ControlId = control.ID;
            NewItem.ControlInstance = control;

            if (control is ListControl)
                NewItem.BindingProperty = "SelectedValue";
            else if (control is CheckBox)
                NewItem.BindingProperty = "Checked";

            DataBindingItems.Add(NewItem);

            return NewItem;
        }
		private static void SetSimpleValueToData(DataBindingItem bindingItem, PropertyInfo piDest, object graph, object targetValue)
		{
			if (graph != null)
				piDest.SetValue(graph, targetValue, null);

			if (bindingItem.CollectToProcessParameters && CurrentProcess != null)
			{
				string parameterName = bindingItem.ProcessParameterName;

				if (parameterName.IsNullOrEmpty())
				{
					if (graph != null)
						parameterName = GetObjectPropertyName(graph.GetType(), bindingItem.DataPropertyName);
					else
						parameterName = bindingItem.DataPropertyName;
				}

				if ((bindingItem.ProcessParameterEvalMode & ProcessParameterEvalMode.CurrentProcess) == ProcessParameterEvalMode.CurrentProcess)
				{
					CurrentProcess.ApplicationRuntimeParameters[parameterName] = targetValue;
				}

				if ((bindingItem.ProcessParameterEvalMode & ProcessParameterEvalMode.ApprovalRootProcess) == ProcessParameterEvalMode.ApprovalRootProcess)
				{
					CurrentProcess.ApprovalRootProcess.ApplicationRuntimeParameters[parameterName] = targetValue;
				}

				if ((bindingItem.ProcessParameterEvalMode & ProcessParameterEvalMode.RootProcess) == ProcessParameterEvalMode.RootProcess)
				{
					CurrentProcess.RootProcess.ApplicationRuntimeParameters[parameterName] = targetValue;
				}

				if ((bindingItem.ProcessParameterEvalMode & ProcessParameterEvalMode.SameResourceRootProcess) == ProcessParameterEvalMode.SameResourceRootProcess)
				{
					CurrentProcess.RootProcess.ApplicationRuntimeParameters[parameterName] = targetValue;
				}
			}
		}
        // <summary>
        /// Creates the text for binding error messages based on the 
        /// BindingErrorMessage property of a data bound control.
        /// 
        /// If set the control calls this method render the error message. Called by 
        /// the various controls to generate the error HTML based on the <see>Enum 
        /// ErrorMessageLocations</see>.
        /// 
        /// If UseClientScriptHtmlInjection is set the error message is injected
        /// purely through a client script JavaScript function which avoids problems
        /// with Controls.Add() when script tags are present in the container.
        /// <seealso>Class wwWebDataHelper</seealso>
        /// </summary>
        /// <param name="control">
        /// Instance of the control that has an error.
        /// </param>
        /// <returns>String</returns>
        internal string GetBindingErrorMessageHtml(DataBindingItem Item)
        {
            string Image = null;
            if (string.IsNullOrEmpty(ErrorIconUrl) || ErrorIconUrl == "WebResource")
                Image = ErrorIconWebResource;
            else
                Image = ResolveClientUrl(ErrorIconUrl);

            string Message = "";

            if (Item.ErrorMessageLocation == BindingErrorMessageLocations.WarningIconRight)
                Message = string.Format("&nbsp;<img src=\"{0}\" title=\"{1}\" />", Image, Item.BindingErrorMessage);
            else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.RedTextBelow)
                Message = "<br /><span style=\"color:red;\"><smaller>" + Item.BindingErrorMessage + "</smaller></span>";
            else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.RedTextAndIconBelow)
                Message = string.Format("<br /><img src=\"{0}\" title=\"{1}\"> <span style=\"color:red;\" /><smaller>{1}</smaller></span>", Image, Item.BindingErrorMessage);
            else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.None)
                Message = "";
            else
                Message = "<span style='color:red;font-weight:bold;'> * </span>";

            
            // Use Client Side JavaScript to inject the message rather than adding a control
            if (UseClientScriptHtmlInjection && Item.ControlInstance != null)
            {
                // Fix up to a JSON string for straight embedding
                Message = WebUtils.EncodeJsString(Message);

                if (!_ClientScriptInjectionScriptAdded)
                    AddScriptForAddHtmlAfterControl();

                ClientScriptProxy.RegisterStartupScript(this,GetType(), Item.ControlId,
                    string.Format("AddHtmlAfterControl(\"{0}\",{1});\r\n", Item.ControlInstance.ClientID, Message), true);

                // Message is handled in script so nothing else to write
                Message = "";
            }


            // Message will be embedded with a Literal Control
            return Message;
        }
		private static void CollectDataFromCheckBoxListToFlagsEnumProperty(DataBindingItem bindingItem, ListItemCollection items, PropertyInfo piDest, object currData)
		{
			if (piDest.CanWrite)
			{
				int targetValue = 0;

				foreach (ListItem item in items)
				{
					int n = 0;

					if (int.TryParse(item.Value, out n))
					{
						if (item.Selected)
							targetValue |= n;
					}
				}

				SetSimpleValueToData(bindingItem, piDest, currData, targetValue);
			}
		}
        /// <summary>
        /// Fires the ValidateControlEvent
        /// </summary>
        /// <param name="Item"></param>
        /// <returns>false - Validation for control failed and a BindingError is added, true - Validation succeeded</returns>
        public bool OnValidateControl(DataBindingItem Item)
        {
            if (ValidateControl != null && !ValidateControl(Item))
                return false;

            return true;
        }
		/// <summary>
		/// 绑定单个控件
		/// </summary>
		/// <param name="dataPropertyInfo">属性</param>
		/// <param name="currData">当前数据</param>
		/// <param name="dataTargetProName">目标属性名称</param>
		/// <param name="item">绑定项</param>
		private void MappingOneDataToOneControl(PropertyInfo dataPropertyInfo, object currData, string dataTargetProName, DataBindingItem item)
		{
			if (currData != null)
			{
				Control targetControl = FindControlByPath(this, item.ControlID);

				//控件对象路径
				string targetPro = string.Empty;
				//控件对象属性
				string targetProName = item.ControlPropertyName;
				ExceptionHelper.FalseThrow(targetControl != null, "不能找到ID为{0}的控件", item.ControlID);

				SplitPath(targetControl, item.ControlPropertyName, out targetPro, out targetProName);

				//获取目标属性值
				object targetItem = FindObjectByPath(targetControl, targetPro);
				if (targetItem != null)
				{
					//获取目标
					PropertyInfo piDest = TypePropertiesCacheQueue.Instance.GetPropertyInfo(targetItem.GetType(),
							GetObjectPropertyName(targetItem.GetType(), targetProName));

					if (piDest != null && piDest.CanWrite)
					{
						//获取绑定属性上的信息,绑定控件属性
						object targetValue = FindObjectByPath(currData, dataTargetProName);
						if (targetValue != null)
						{
							if (SetControlsAttributesByDataType(dataPropertyInfo, targetValue, targetItem, item, targetProName) == false)
							{
								targetValue = FormatDataProperty(targetValue, piDest, item);
								piDest.SetValue(targetItem, targetValue, null);
							}
						}
					}
				}
			}
		}
        /// <summary>
        /// Add a DataBindingItem to the collection
        /// </summary>
        /// <param name="index"></param>
        /// <param name="Item"></param>
        public void AddAt(int index, DataBindingItem Item)
        {
            if (_ParentDataBinder != null)
            {
                Item.Page = _ParentDataBinder.Page;
                Item.Binder = _ParentDataBinder;

               // VS Designer adds new items as soon as their accessed
                // but items may not be valid so we have to clean up
                if (_ParentDataBinder.DesignMode)
                {
                   UpdateListInDesignMode();
                }
            }

            InnerList.Insert(index, Item);
        }
		/// <summary>
		/// 设置控件属性
		/// </summary>
		/// <param name="dataPropertyInfo"></param>
		/// <param name="data"></param>
		/// <param name="control"></param>
		/// <param name="item"></param>
		/// <param name="targetProName"></param>
		/// <returns></returns>
		private bool SetControlsAttributesByDataType(PropertyInfo dataPropertyInfo, object data, object control, DataBindingItem item, string targetProName)
		{
			bool binded = false;
			if (data == null || (control is ListControl && data.ToString().Length <= 0))
				return binded;	//防止对ListControl进行空值绑定,导致错误。

			if (dataPropertyInfo.PropertyType.IsEnum)
			{
				if (control is ListControl)
				{
					BindEnumToListControl(dataPropertyInfo.PropertyType, data, (ListControl)control, item);
					binded = true;
				}
				else if (control is ITextControl)
				{
					BindEnumToTextControl(data, (ITextControl)control, item);
					binded = true;
				}
			}

			//特殊处理:如果绑定的是List控件的Items的属性,应置成选中,而不是设置它的值。
			if (control is ListItem)
			{
				control = this.FindControl(item.ControlID);

				if (targetProName.ToLower() == "text")
				{
					foreach (ListItem litem in ((ListControl)control).Items)
					{
						if (litem.Text.ToLower() == data.ToString().ToLower())
						{
							litem.Selected = true;
						}
						else
						{
							litem.Selected = false;
						}
					}
				}
				else if (targetProName.ToLower() == "value")
				{
					((ListControl)control).SelectedValue = data.ToString();
				}
				binded = true;
			}

			return binded;
		}
		public ClientDataBindingItem(DataBindingItem item)
		{
			CopyFromBindingItem(item);
		}