//==============================================================
//  版权所有：深圳杰文科技
//  文件名：BindingSourceExt.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Infrastructure.Components
{
	[DebuggerStepThrough]
	public static class BindingSourceExt
	{
		public static T GetCurrent<T>(this BindingSource bindingSource)
		{
			if (bindingSource.Count == 0 || bindingSource.Position < 0 || bindingSource.Current == null)
			{
				return default(T);
			}

			return (T)bindingSource.Current;
		}

		public static void ReplaceCurrent(this BindingSource bindingSource, object newObject)
		{
			if (bindingSource.Current != null)
			{
				int idx = bindingSource.Position;
				bindingSource.RemoveCurrent();
				bindingSource.Insert(idx, newObject);
				bindingSource.Position = idx;
				bindingSource.ResetCurrentItem();
			}
		}

		public static List<T> AsList<T>(this BindingSource bindingSource) where T : class ,new()
		{
			List<T> list = bindingSource.DataSource as List<T>;
			return list;
		}

		public static void SetDataSource<T>(this BindingSource bindingSource, T obj) where T : class, new()
		{
			if (obj == null)
			{
				bindingSource.DataSource = typeof(T);
			}
			else
			{
				bindingSource.DataSource = obj;
			}
		}

		public static void SetDataSource<T>(this BindingSource bindingSource, IEnumerable<T> list) where T : class, new()
		{
			if (list == null)
			{
				bindingSource.DataSource = typeof(T);
			}
			else
			{
				bindingSource.DataSource = list;
			}
		}
	}
}
