//using System.Windows.Forms;
using Infragistics.Excel;
using Infragistics.Win;
using Infragistics.Win.Layout;
using Infragistics.Win.Misc;
using Infragistics.Win.UltraWinDataSource;
using Infragistics.Win.UltraWinEditors;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.UltraWinGrid.ExcelExport;
using Infragistics.Win.UltraWinTabControl;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Common
{
    /// <summary>
    /// 控件设置、属性相关公用
    /// </summary>
    public class ClsControlPack
    {
        private Log mylog = Log.GetInstance();

        /// <summary>
        /// 获取子窗体弹出的位置坐标
        /// </summary>
        /// <param name="ChildWindowSize"></param>
        /// <returns></returns>
        public static Point GetChildWindowLocation(Size ChildWindowSize)
        {
            Point point = Cursor.Position;
            Size size = Cursor.Current.Size;
            int width = point.X + ChildWindowSize.Width - Screen.PrimaryScreen.Bounds.Width;
            int height = point.Y + ChildWindowSize.Height - Screen.PrimaryScreen.Bounds.Height;
            width = (width > 0) ? (point.X - width - size.Width) : point.X;                      // X坐标
            height = (height > 0) ? (point.Y - height - size.Height) : point.Y;            // Y坐标
            return new Point(width, height);
        }

        /// <summary>
        /// 按字段，过滤UltraGrid信息
        /// </summary>
        /// <param name="ug"></param>
        /// <param name="columnName"></param>
        /// <param name="filter"></param>
        public static void SetUltraGridFilter(UltraGrid ug, string columnName, string filter)
        {
            if (ug != null && ug.Rows.Count > 0)
            {
                ug.DisplayLayout.Bands[0].ColumnFilters[columnName].FilterConditions.Clear();

                if (!string.IsNullOrEmpty(filter))
                {
                    ug.DisplayLayout.Bands[0].ColumnFilters[columnName].FilterConditions.Add(
                         Infragistics.Win.UltraWinGrid.FilterComparisionOperator.Contains, filter);
                }
            }
        }

        public static void ClearUltraGridFilter(UltraGrid ug)
        {
            if (ug != null)
            {
                ug.DisplayLayout.Bands[0].ColumnFilters.ClearAllFilters();
            }
        }

        /// <summary>
        /// DataTable数据拷贝
        /// </summary>
        /// <param name="src">源</param>
        /// <param name="dest">目标</param>
        /// <param name="ClearExists">是否清除目标DataTable现有数据</param>
        public static void CopyDataToDatatable(ref DataTable src, ref DataTable dest, bool ClearExists)
        {
            try
            {
                if (src == null)
                {
                    dest = null;
                    return;
                }

                if (dest == null)
                {
                    dest = new DataTable();
                }

                if (ClearExists)
                {
                    if (dest != null) dest.Rows.Clear();
                }

                DataRow CurRow, NewRow;

                if (src != null && src.Rows != null && src.Rows.Count > 0)
                    for (int i = 0; i < src.Rows.Count; i++)
                    {
                        CurRow = src.Rows[i];
                        NewRow = dest.NewRow();

                        for (int j = 0; j < src.Columns.Count; j++)
                        {
                            try
                            {
                                if (dest.Columns.Contains(src.Columns[j].ColumnName))
                                {
                                    NewRow[src.Columns[j].ColumnName] = CurRow[j];
                                }
                            }
                            catch { }
                        }

                        dest.Rows.Add(NewRow);
                    }

                dest.AcceptChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show("公共方法CopyDataToDatatable报错！错误内容：\r\n" + ex.Message);
            }
        }

        /// <summary>
        /// UltraGrid列宽自适应
        /// </summary>
        /// <param name="ultraGrid"></param>
        public static void RefreshAndAutoSize(UltraGrid ultraGrid, bool childFlag = false)
        {
            int count = 0;
            try
            {
                count = 1;
                /**
                ultraGrid.BeginUpdate();
                if (ultraGrid != null && ultraGrid.Rows.Count > 0)
                {
                    foreach (UltraGridBand band in ultraGrid.DisplayLayout.Bands)
                    {
                        foreach (UltraGridColumn column in band.Columns)
                        {
                            column.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, band.ColHeadersVisible ? true : false);
                        }
                    }
                }
                 ultraGrid.EndUpdate();
                */
                if (ultraGrid==null || ultraGrid.Rows  ==null || ultraGrid.Rows.Count == 0)
                {
                    ultraGrid.Update();
                    ultraGrid.Refresh();
                    return;
                }
                ultraGrid.DataBind(); //此行代码会报错，暂未解决；
                count = 2;
                ultraGrid.Update();
                count = 3;
                bool childbandsAutoSize = childFlag; //引用的浩鑫的代码；默认为false
                if (childbandsAutoSize)
                {
                    foreach (UltraGridBand band in ultraGrid.DisplayLayout.Bands)
                    {
                        count = 4;
                        if (band.Index > 0)
                        {
                            count = 5;
                            band.RowLayoutStyle = RowLayoutStyle.GroupLayout;
                        }
                        count = 6;
                        band.PerformAutoResizeColumns(true, PerformAutoSizeType.AllRowsInBand);
                    }
                }
                else
                {
                    foreach (UltraGridBand band in ultraGrid.DisplayLayout.Bands)
                    {
                        count = 7;
                        band.PerformAutoResizeColumns(true, PerformAutoSizeType.VisibleRows);
                    }
                }
                count = 8;
                ultraGrid.Refresh();
                count = 9;
            }
            catch (Exception ex)
            {
               // MessageBox.Show(ultraGrid.Name + "公共方法RefreshAndAutoSize报错,位置【" + count + "】！错误内容：\r\n" + ex.Message);
            }
        }

        /// <summary>
        /// 设置UltraComboEditor项目集合
        /// </summary>
        /// <param name="cbEdt"></param>
        /// <param name="vlist"></param>
        /// <param name="bNull">是否加入空项</param>
        /// <returns></returns>
        public static bool SetUltraComboEditor(ref UltraComboEditor cbEdt, ref ValueList vlist, bool bNull)
        {
            if (cbEdt == null || vlist == null)
                return false;

            cbEdt.Items.Clear();

            if (bNull)
                cbEdt.Items.Add(null, "");

            for (int i = 0; i < vlist.ValueListItems.Count; i++)
            {
                try
                {
                    cbEdt.Items.Add(vlist.ValueListItems[i].DataValue, vlist.ValueListItems[i].DisplayText);
                }
                catch { }
            }

            return true;
        }

        /// <summary>
        /// 载入下拉框中的数据
        /// </summary>
        /// <param name="cmb"></param>
        /// <param name="table"></param>
        /// <param name="ColumnValue"></param>
        /// <param name="ColumnDisplay"></param>
        public static void SetUltraComboDataSource(UltraCombo cmb, DataTable table, string ColumnValue, string ColumnDisplay)
        {
            if (table == null || !table.Columns.Contains(ColumnValue) || !table.Columns.Contains(ColumnDisplay)) return;
            try
            {
                if (cmb != null)
                {
                    cmb.DataSource = table;
                    cmb.DisplayLayout.Override.TipStyleScroll = TipStyle.Hide;
                    cmb.DisplayLayout.Override.BorderStyleCell = UIElementBorderStyle.None;
                    cmb.DisplayLayout.Override.BorderStyleRow = UIElementBorderStyle.None;
                    cmb.DisplayLayout.Override.SelectTypeRow = SelectType.Single;
                    cmb.DisplayLayout.Override.HeaderStyle = HeaderStyle.Standard;
                    cmb.DisplayLayout.Override.HeaderAppearance.TextHAlign = HAlign.Center;
                    cmb.DisplayLayout.Override.RowAppearance.TextVAlign = VAlign.Middle;
                    cmb.DisplayLayout.Override.ActiveRowAppearance.BackColor = Color.FromArgb(51, 153, 255);
                    cmb.DisplayLayout.Override.ActiveRowAppearance.ForeColor = Color.FromArgb(255, 255, 255);
                    cmb.DisplayLayout.Override.SelectedRowAppearance.BackColor = Color.FromArgb(51, 153, 255);
                    cmb.DisplayLayout.Override.SelectedRowAppearance.ForeColor = Color.FromArgb(255, 255, 255);
                    //cmb.DisplayLayout.Override.ActiveRowAppearance.FontData.Bold = DefaultableBoolean.True;
                    foreach (UltraGridBand band in cmb.DisplayLayout.Bands)
                    {
                        band.ColHeadersVisible = false;
                        foreach (UltraGridColumn column in band.Columns)
                        {
                            if (!column.Key.Equals(ColumnDisplay)) column.Hidden = true;
                            column.Width = cmb.Width;
                            //column.PerformAutoResize(PerformAutoSizeType.AllRowsInBand);
                        }
                    }
                    cmb.ValueMember = ColumnValue;
                    cmb.DisplayMember = ColumnDisplay;
                    cmb.DropDownWidth = -1;
                }
            }
            catch { }
        }

        public static ArrayList GetSelectedRows(UltraGrid ug, string ColumnName, bool IncludeFilterOut = true)
        {
            int BandIndex = 0;
            ArrayList selectedRows = new ArrayList();
            try
            {
                if (!ug.DisplayLayout.Bands[BandIndex].Columns.Exists(ColumnName)) return selectedRows;
                if (!ug.DisplayLayout.Bands[BandIndex].Columns.Exists("UNCK")) return selectedRows;

                for (int idx = 0; idx < ug.Rows.Count; idx++)
                {
                    UltraGridRow ur = ug.Rows[idx];

                    if (ur.IsFilteredOut && !IncludeFilterOut) continue;

                    object v = ur.GetCellValue(ug.DisplayLayout.Bands[BandIndex].Columns["UNCK"]);

                    if (v.GetType() == typeof(Boolean) || v.GetType() == typeof(bool))
                    {
                        if ((bool)v) selectedRows.Add(ur.GetCellText(ug.DisplayLayout.Bands[BandIndex].Columns[ColumnName]));
                    }
                    else if (v.GetType() == typeof(string) || v.GetType() == typeof(String))
                    {
                        if (!(v.ToString().ToUpper() == "FALSE" || v.ToString().ToUpper() == "0"))
                            selectedRows.Add(ur.GetCellText(ug.DisplayLayout.Bands[BandIndex].Columns[ColumnName]));
                    }
                    else
                    {
                        if (((int)v) != 0)
                            selectedRows.Add(ur.GetCellText(ug.DisplayLayout.Bands[BandIndex].Columns[ColumnName]));
                    }
                }
                return selectedRows;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Clean方法异常，请关闭界面并稍后打开，或联系管理员" + ex);
                return selectedRows;
            }
        }

        /// <summary>
        /// 设置ultraGrid的激活单元格
        /// </summary>
        /// <param name="ultraGrid"></param>
        /// <param name="RowIndexNo"></param>
        /// <param name="ColumnName"></param>
        /// <param name="EnterEditMode"></param>
        public static void SetUltraGridActiveCell(ref UltraGrid ultraGrid, int RowIndexNo, string ColumnName, bool EnterEditMode)
        {
            try
            {
                if (ultraGrid != null && RowIndexNo >= 0 && ultraGrid.Rows.Count >= RowIndexNo + 1)
                {
                    ultraGrid.ActiveCell = ultraGrid.Rows[RowIndexNo].Cells[ColumnName];

                    if (EnterEditMode)
                        ultraGrid.PerformAction(UltraGridAction.EnterEditMode);
                }
            }
            catch { }
        }

        #region ultraGrid设置

        public static void ClearEvent(Control control, string eventname)
        {
            if (control == null) return;
            if (string.IsNullOrEmpty(eventname)) return;

            BindingFlags mPropertyFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic;
            BindingFlags mFieldFlags = BindingFlags.Static | BindingFlags.NonPublic;
            Type controlType = typeof(Control);
            PropertyInfo propertyInfo = controlType.GetProperty("Events", mPropertyFlags);
            EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(control, null);
            FieldInfo fieldInfo = (typeof(System.Windows.Forms.Control)).GetField("Event" + eventname, mFieldFlags);
            Delegate d = eventHandlerList[fieldInfo.GetValue(control)];

            if (d == null) return;
            EventInfo eventInfo = controlType.GetEvent(eventname);

            foreach (Delegate dx in d.GetInvocationList())
                eventInfo.RemoveEventHandler(control, dx);
        }

        public static void SetUltraGridStyle(Control Parent, bool AutoSizeUltraGrid)
        {
            UltraGrid grid = null;

            foreach (Control ctrl in Parent.Controls)
            {
                try
                {
                    if (ctrl.GetType().Equals(typeof(UltraGrid)))
                    {
                        grid = (UltraGrid)ctrl;
                        if (grid == null) continue;

                        try
                        {
                            if (grid.DisplayLayout.Bands.Count > 0)
                            {
                                if (grid.DisplayLayout.Bands[0].CardView)
                                {
                                    grid.DisplayLayout.Appearance.ResetBorderColor();
                                    grid.DisplayLayout.BorderStyle = UIElementBorderStyle.None;
                                    grid.DisplayLayout.Override.CardAreaAppearance.BackColor = _BACKCOLOR;
                                    grid.DisplayLayout.Override.CardAreaAppearance.BackColor2 = _BACKCOLOR;
                                    grid.DisplayLayout.Override.HeaderAppearance.BackColor = _BACKCOLOR;
                                    grid.DisplayLayout.Override.HeaderAppearance.BackColor2 = _BACKCOLOR;
                                    grid.DisplayLayout.Override.BorderStyleRow = UIElementBorderStyle.None;
                                }
                                else
                                {
                                    grid.DisplayLayout.UseFixedHeaders = true;
                                    grid.DisplayLayout.BorderStyle = UIElementBorderStyle.Default;
                                    grid.DisplayLayout.Appearance.BorderColor = Color.DarkGray;
                                    grid.DisplayLayout.ViewStyleBand = ViewStyleBand.Vertical;
                                    grid.DisplayLayout.GroupByBox.Prompt = "将需要分组的列拖到此处";
                                    grid.DisplayLayout.Override.MaxSelectedRows = 0;
                                    grid.DisplayLayout.Override.SelectTypeRow = SelectType.Single;
                                    grid.DisplayLayout.Override.SelectTypeCol = SelectType.None;
                                    grid.DisplayLayout.Override.BorderStyleCell = UIElementBorderStyle.Solid;
                                    grid.DisplayLayout.Override.BorderStyleRow = UIElementBorderStyle.Solid;
                                    grid.DisplayLayout.Override.WrapHeaderText = DefaultableBoolean.False;

                                    grid.DisplayLayout.Override.DataErrorRowAppearance.BackColor = Color.Lime;
                                    grid.DisplayLayout.Override.SupportDataErrorInfo = SupportDataErrorInfo.RowsOnly;

                                    grid.DisplayLayout.Override.HeaderStyle = HeaderStyle.Standard;
                                    grid.DisplayLayout.Override.RowSelectorStyle = HeaderStyle.Standard;
                                    grid.DisplayLayout.Override.MinRowHeight = 22;
                                    //grid.DisplayLayout.Override.RowSelectorNumberStyle = RowSelectorNumberStyle.RowIndex;
                                    grid.DisplayLayout.Override.RowSelectorWidth = 35;
                                    grid.DisplayLayout.Override.CellClickAction = CellClickAction.EditAndSelectText;

                                    grid.DisplayLayout.Override.ActiveRowAppearance.FontData.Bold = DefaultableBoolean.True;
                                    grid.DisplayLayout.Override.ActiveRowAppearance.ForeColor = Color.Empty;
                                    grid.DisplayLayout.Override.ActiveRowAppearance.BackColor = Color.Empty;

                                    grid.DisplayLayout.Override.DataErrorRowAppearance.ForeColor = Color.Empty;
                                    grid.DisplayLayout.Override.DataErrorRowAppearance.BackColor = Color.Empty;

                                    grid.DisplayLayout.Override.RowAppearance.BackColor = Color.White;
                                    grid.DisplayLayout.Override.RowAppearance.BorderColor = Color.DarkGray;
                                    grid.DisplayLayout.Override.RowAppearance.TextVAlign = VAlign.Middle;
                                    grid.DisplayLayout.Override.RowAlternateAppearance.BackColor = Color.FromArgb(229, 255, 229);

                                    grid.DisplayLayout.Override.RowSelectorAppearance.TextVAlign = VAlign.Middle;
                                    grid.DisplayLayout.Override.HeaderAppearance.BackColor = Color.FromArgb(183, 208, 250);
                                    grid.DisplayLayout.Override.HeaderAppearance.BackColor2 = Color.FromArgb(183, 208, 250);
                                    grid.DisplayLayout.Override.RowSelectorAppearance.BackColor = Color.FromArgb(183, 208, 250);
                                    grid.DisplayLayout.Override.RowSelectorAppearance.BackColor2 = Color.FromArgb(183, 208, 250);
                                }
                            }
                        }
                        catch { }

                        try
                        {
                            if (grid.DisplayLayout.Bands.Count > 1)
                            {
                                grid.DisplayLayout.Bands[1].Override.HeaderAppearance.BackColor = Color.FromArgb(233, 242, 199);
                                grid.DisplayLayout.Bands[1].Override.HeaderAppearance.BackColor2 = Color.FromArgb(170, 184, 131);
                                grid.DisplayLayout.Bands[1].Override.HeaderAppearance.BackGradientStyle = GradientStyle.Vertical;

                                grid.DisplayLayout.Bands[1].Override.RowSelectorAppearance.BackColor = Color.FromArgb(233, 242, 199);
                                grid.DisplayLayout.Bands[1].Override.RowSelectorAppearance.BackColor2 = Color.FromArgb(170, 184, 131);
                                grid.DisplayLayout.Bands[1].Override.RowSelectorAppearance.BackGradientStyle = GradientStyle.Vertical;
                            }
                        }
                        catch { }

                        try
                        {
                            foreach (UltraGridBand band in grid.DisplayLayout.Bands)
                            {
                                band.Override.AllowRowLayoutCellSizing = RowLayoutSizing.None;
                                band.Override.AllowRowLayoutCellSpanSizing = GridBagLayoutAllowSpanSizing.None;
                                band.Override.AllowRowLayoutColMoving = GridBagLayoutAllowMoving.None;
                                band.Override.AllowRowLayoutLabelSizing = (band.CardView ? RowLayoutSizing.None : RowLayoutSizing.Horizontal);
                                band.Override.AllowRowLayoutLabelSpanSizing = GridBagLayoutAllowSpanSizing.None;
                            }
                        }
                        catch { }

                        try
                        {
                            grid.KeyDown += new KeyEventHandler(grid_KeyDown);
                        }
                        catch { }

                        //平台中加了此事件
                        try
                        {
                            grid.DoubleClickCell += new DoubleClickCellEventHandler(grid_DoubleClickCell);
                        }
                        catch { }

                        //平台中加了此事件
                        try
                        {
                            grid.BeforeRowsDeleted += new BeforeRowsDeletedEventHandler(grid_BeforeRowsDeleted);
                        }
                        catch { }

                        if (AutoSizeUltraGrid && !grid.DisplayLayout.Bands[0].CardView)
                            RefreshAndAutoSize(grid);
                    }
                    else
                    {
                        SetUltraGridStyle(ctrl, AutoSizeUltraGrid);
                    }
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.Message);
                }
            }
        }

        public static void SetSelectColumnStyle(UltraGrid grid)
        {
            if (grid == null) return;

            foreach (UltraGridBand gb in grid.DisplayLayout.Bands)
            {
                if (gb.Columns.Exists("Selected"))
                {
                    UltraGridColumn uc = gb.Columns["Selected"];
                    uc.AllowGroupBy = Infragistics.Win.DefaultableBoolean.False;
                    uc.CellClickAction = Infragistics.Win.UltraWinGrid.CellClickAction.Edit;
                    uc.DataType = typeof(bool);
                    uc.DefaultCellValue = false;
                    uc.Header.Caption = "";
                    uc.Header.CheckBoxVisibility = Infragistics.Win.UltraWinGrid.HeaderCheckBoxVisibility.Always;
                    uc.RowLayoutColumnInfo.OriginX = 0;
                    uc.RowLayoutColumnInfo.OriginY = 0;
                    uc.RowLayoutColumnInfo.PreferredCellSize = new System.Drawing.Size(40, 0);
                    uc.RowLayoutColumnInfo.SpanX = 1;
                    uc.RowLayoutColumnInfo.SpanY = 1;
                    uc.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;
                }
            }
        }

        private static void grid_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                UltraGrid grid = (UltraGrid)sender;
                if (grid == null) return;
                UltraGridCell cell = grid.ActiveCell;
                if (cell == null) return;

                bool bOK = false;
                int iRow = cell.Row.Index;
                int iColumn = cell.Column.Index;

                if (e.KeyCode == Keys.Up)
                {
                    iRow--;
                    if (iRow >= 0)
                        bOK = true;
                }
                else if (e.KeyCode == Keys.Down)
                {
                    iRow++;
                    if (cell.Band.Index == 0)
                    {
                        if (iRow <= grid.Rows.Count - 1)
                            bOK = true;
                    }
                    else
                    {
                        if (iRow <= cell.Row.ParentRow.ChildBands[cell.Band.Key].Rows.Count - 1)
                            bOK = true;
                    }
                }
                else if (e.KeyCode == Keys.Left)
                {
                    grid.PerformAction(UltraGridAction.PrevCellByTab);
                }
                else if (e.KeyCode == Keys.Right)
                {
                    grid.PerformAction(UltraGridAction.NextCellByTab);
                }

                if (bOK)
                {
                    if (cell.Band.Index == 0)
                        grid.ActiveCell = grid.Rows[iRow].Cells[iColumn];
                    else
                        grid.ActiveCell = cell.Row.ParentRow.ChildBands[cell.Band.Key].Rows[iRow].Cells[iColumn];
                    grid.PerformAction(UltraGridAction.EnterEditMode);
                }
            }
            catch { }
        }

        private static void grid_DoubleClickCell(object sender, DoubleClickCellEventArgs e)
        {
            try
            {
                if (e.Cell.Row.HasChild())
                {
                    if (e.Cell.Row.IsExpanded)
                        e.Cell.Row.CollapseAll();
                    else
                        e.Cell.Row.ExpandAll();
                }
            }
            catch { }
        }

        private static void grid_BeforeRowsDeleted(object sender, BeforeRowsDeletedEventArgs e)
        {
            e.DisplayPromptMsg = false;
        }

        #endregion ultraGrid设置

        /// <summary>
        /// 设置UltraGrid指定列的ValueList
        /// </summary>
        /// <param name="myGrid"></param>
        /// <param name="strColumn"></param>
        /// <param name="vlist"></param>
        public static void SetGridValuelist(ref UltraGrid myGrid, string strColumn, ref ValueList vlist)
        {
            SetGridValuelist(ref myGrid, 0, strColumn, ref vlist);
        }

        /// <summary>
        /// 设置UltraGrid指定列的ValueList，指定Band
        /// </summary>
        /// <param name="myGrid"></param>
        /// <param name="BandIndex"></param>
        /// <param name="strColumn"></param>
        /// <param name="vlist"></param>
        public static void SetGridValuelist(ref UltraGrid myGrid, int BandIndex, string strColumn, ref ValueList vlist)
        {
            bool Contains = GridContainsColumn(myGrid, BandIndex, strColumn);
            try
            {
                if (Contains)
                {
                    myGrid.DisplayLayout.Bands[BandIndex].Columns[strColumn].ValueList = vlist;
                    //myGrid.DisplayLayout.Bands[BandIndex].Columns[strColumn].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDown;
                }
            }
            catch { }
        }

        /// <summary>
        /// 根据指定DataTable生成ValueList
        /// </summary>
        /// <param name="table"></param>
        /// <param name="strKey">value</param>
        /// <param name="strText">Text</param>
        /// <returns></returns>
        public static ValueList GeneralValuelist(ref DataTable table, string strKey, string strText)
        {
            if (table == null || !table.Columns.Contains(strKey) || !table.Columns.Contains(strText))
                return new ValueList();
            ArrayList alist = new ArrayList();
            ValueList vlist = new ValueList();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                try
                {
                    if (!alist.Contains(table.Rows[i][strKey]))
                    {
                        alist.Add(table.Rows[i][strKey]);
                        vlist.ValueListItems.Add(table.Rows[i][strKey], Convert.ToString(table.Rows[i][strText]));
                    }
                }
                catch { }
            }
            return vlist;
        }

        public static void InitUltraDataSource(UltraDataSource ultDataSource)
        {
            try
            {
                int iColumnsCount = ultDataSource.Band.Columns.Count;
                object[] obj = new object[iColumnsCount];

                if (ultDataSource.Rows.Count > 0) ultDataSource.Rows.Clear();

                for (int i = 0; i < ultDataSource.Band.Columns.Count; i++)
                {
                    try
                    {
                        if (ultDataSource.Band.Columns[i].DataType == typeof(Bitmap) ||
                            ultDataSource.Band.Columns[i].DataType == typeof(Image))
                            obj[i] = null;
                        else if (ultDataSource.Band.Columns[i].DataType == typeof(DateTime))
                            obj[i] = DBNull.Value;
                        else if (ultDataSource.Band.Columns[i].DataType == typeof(decimal) ||
                                ultDataSource.Band.Columns[i].DataType == typeof(double) ||
                                ultDataSource.Band.Columns[i].DataType == typeof(Single))
                            obj[i] = 0;
                        else
                            obj[i] = "";
                    }
                    catch { }
                }
                ultDataSource.Rows.Add(obj);
            }
            catch { }
        }

        /// <summary>
        /// 初始化UltraDataSource
        /// </summary>
        /// <param name="ultDataSource"></param>
        public static void InitUserControl(UltraDataSource ultDataSource, UltraGrid ultraGrid)
        {
            try
            {
                InitUltraDataSource(ultDataSource);
                ultraGrid.UpdateData();
            }
            catch { }
        }

        /// <summary>
        /// UltraDataSource数据重置
        /// </summary>
        /// <param name="ultDataSource"></param>
        public static void ResetUltraDataSource(UltraDataSource ultDataSource)
        {
            try
            {
                if (ultDataSource.Rows.Count == 0)
                {
                    InitUltraDataSource(ultDataSource);
                    return;
                }

                for (int i = 0; i < ultDataSource.Band.Columns.Count; i++)
                {
                    try
                    {
                        if (ultDataSource.Band.Columns[i].DataType == typeof(Bitmap) ||
                            ultDataSource.Band.Columns[i].DataType == typeof(Image))
                            ultDataSource.Rows[0][i] = null;
                        else if (ultDataSource.Band.Columns[i].DataType == typeof(DateTime))
                            ultDataSource.Rows[0][i] = DBNull.Value;
                        else if (ultDataSource.Band.Columns[i].DataType == typeof(decimal) ||
                            ultDataSource.Band.Columns[i].DataType == typeof(double) ||
                            ultDataSource.Band.Columns[i].DataType == typeof(Single))
                            ultDataSource.Rows[0][i] = 0;
                        else
                            ultDataSource.Rows[0][i] = "";
                    }
                    catch { }
                }
            }
            catch { }
        }

        /// <summary>
        /// UltraDataSource数据重置
        /// </summary>
        /// <param name="ultDataSource"></param>
        public static void ResetUltraDataSource(UltraDataSource ultDataSource, UltraGrid ultraGrid)
        {
            try
            {
                ResetUltraDataSource(ultDataSource);
            }
            catch { }
            finally
            {
                if (ultraGrid != null)
                    ultraGrid.UpdateData();
            }
        }

        /// <summary>
        /// ultraGrid设置Cell只读属性
        /// </summary>
        /// <param name="ultraGrid"></param>
        /// <param name="bReadOnly"></param>
        public static void SetUltraGridCellReadOnly(ref UltraGrid ultraGrid, bool bReadOnly)
        {
            try
            {
                for (int i = 0; i < ultraGrid.DisplayLayout.Bands[0].Columns.Count; i++)
                {
                    ultraGrid.DisplayLayout.Bands[0].Columns[i].CellActivation = (bReadOnly ? Activation.ActivateOnly : Activation.AllowEdit);
                    ultraGrid.DisplayLayout.Bands[0].Columns[i].CellAppearance.BackColor = (bReadOnly ? Color.LightBlue : Color.White);
                }
            }
            catch { }
        }

        /// <summary>
        /// UltraDataSource是否包含strColumnName列
        /// </summary>
        /// <param name="ultDataSource"></param>
        /// <param name="strColumnName"></param>
        /// <returns></returns>
        public static bool UltraDataSourceContainsColumn(ref UltraDataSource ultDataSource, string strColumnName)
        {
            try
            {
                for (int i = 0; i < ultDataSource.Band.Columns.Count; i++)
                {
                    if (ultDataSource.Band.Columns[i].Key == strColumnName)
                        return true;
                }
            }
            catch { }

            return false;
        }

        public static bool GridContainsColumn(UltraGrid grid, string strColumn)
        {
            return GridContainsColumn(grid, 0, strColumn);
        }

        public static bool GridContainsColumn(UltraGridBand band, string strColumn)
        {
            for (int i = 0; i < band.Columns.Count; i++)
            {
                if (band.Columns[i].Key.Equals(strColumn))
                    return true;
            }
            return false;
        }

        public static bool GridContainsColumn(UltraGrid grid, int BandIndex, string strColumn)
        {
            if (BandIndex <= grid.DisplayLayout.Bands.Count - 1)
            {
                for (int i = 0; i < grid.DisplayLayout.Bands[BandIndex].Columns.Count; i++)
                {
                    if (grid.DisplayLayout.Bands[BandIndex].Columns[i].Key.Equals(strColumn))
                        return true;
                }
            }
            return false;
        }

        public static void SetGridGroupBy(ref UltraGrid myGrid1, bool bAllowGroupBy)
        {
            try
            {
                if (!bAllowGroupBy)
                {
                    for (int i = 0; i < myGrid1.DisplayLayout.Bands[0].Columns.Count; i++)
                    {
                        try
                        {
                            if (myGrid1.DisplayLayout.Bands[0].Columns[i].IsGroupByColumn)
                                myGrid1.DisplayLayout.Bands[0].Columns[i].ResetIsGroupByColumn();
                        }
                        catch { }
                    }
                }
                myGrid1.DisplayLayout.GroupByBox.Hidden = !bAllowGroupBy;
            }
            catch { }
        }

        public static void SetUltraGridRowFilter(ref UltraGrid myGrid1, bool bAllowFilter)
        {
            try
            {
                if (bAllowFilter)
                {
                    if (myGrid1.DisplayLayout.Override.FilterUIType != FilterUIType.FilterRow)
                        myGrid1.DisplayLayout.Override.FilterUIType = FilterUIType.FilterRow;

                    for (int i = 0; i < myGrid1.DisplayLayout.Bands.Count; i++)
                    {
                        for (int j = 0; j < myGrid1.DisplayLayout.Bands[i].Columns.Count; j++)
                        {
                            try
                            {
                                if (!myGrid1.DisplayLayout.Bands[i].Columns[j].Hidden && myGrid1.DisplayLayout.Bands[i].Columns[j].RowLayoutColumnInfo.LabelPosition != LabelPosition.LabelOnly)
                                {
                                    //string sKey = myGrid1.DisplayLayout.Bands[i].Columns[j].Key; //UNCK  UNCH
                                    myGrid1.DisplayLayout.Bands[i].Columns[j].AllowRowFiltering = Infragistics.Win.DefaultableBoolean.True;
                                }
                            }
                            catch { }
                        }
                    }
                }
                else
                {
                    if (myGrid1.DisplayLayout.Override.FilterUIType != FilterUIType.HeaderIcons)
                        myGrid1.DisplayLayout.Override.FilterUIType = FilterUIType.HeaderIcons;

                    for (int i = 0; i < myGrid1.DisplayLayout.Bands.Count; i++)
                    {
                        try
                        {
                            myGrid1.DisplayLayout.Bands[i].ColumnFilters.ClearAllFilters();
                        }
                        catch { }

                        for (int j = 0; j < myGrid1.DisplayLayout.Bands[i].Columns.Count; j++)
                        {
                            try
                            {
                                myGrid1.DisplayLayout.Bands[i].Columns[j].AllowRowFiltering = Infragistics.Win.DefaultableBoolean.False;
                            }
                            catch { }
                        }
                    }
                }
            }
            catch { }
        }

        public static void SetGridColumnsReadOnly(ref UltraGrid ultraGrid, ArrayList alistAllowEdit, ArrayList alistActivateOnly, ArrayList alistNoEdit, ArrayList alistDisabled)
        {
            try
            {
                for (int i = 0; i < ultraGrid.Rows.Count; i++)
                {
                    if (alistAllowEdit != null && alistAllowEdit.Count > 0)
                    {
                        for (int j = 0; j < alistAllowEdit.Count; j++)
                        {
                            try
                            {
                                if (GridContainsColumn(ultraGrid, alistAllowEdit[j].ToString()))
                                {
                                    ultraGrid.Rows[i].Cells[alistAllowEdit[j].ToString()].Activation = Activation.AllowEdit;
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                        }
                    }

                    if (alistActivateOnly != null && alistActivateOnly.Count > 0)
                    {
                        for (int j = 0; j < alistActivateOnly.Count; j++)
                        {
                            try
                            {
                                if (GridContainsColumn(ultraGrid, alistActivateOnly[j].ToString()))
                                {
                                    ultraGrid.Rows[i].Cells[alistActivateOnly[j].ToString()].Activation = Activation.ActivateOnly;
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                        }
                    }

                    if (alistNoEdit != null && alistNoEdit.Count > 0)
                    {
                        for (int j = 0; j < alistNoEdit.Count; j++)
                        {
                            try
                            {
                                if (GridContainsColumn(ultraGrid, alistNoEdit[j].ToString()))
                                {
                                    ultraGrid.Rows[i].Cells[alistNoEdit[j].ToString()].Activation = Activation.NoEdit;
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                        }
                    }

                    if (alistDisabled != null && alistDisabled.Count > 0)
                    {
                        for (int j = 0; j < alistDisabled.Count; j++)
                        {
                            try
                            {
                                if (GridContainsColumn(ultraGrid, alistDisabled[j].ToString()))
                                {
                                    ultraGrid.Rows[i].Cells[alistDisabled[j].ToString()].Activation = Activation.Disabled;
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        public static bool HasCheckedRows(ref UltraGrid ultraGrid, string strColumnCondition, object value, string strOutColumn, out ArrayList alistValue, out string strMsg)
        {
            strMsg = "";
            alistValue = new ArrayList();

            try
            {
                if (ultraGrid == null || ultraGrid.Rows.Count == 0)
                {
                    return false;
                }

                if (!string.IsNullOrEmpty(strColumnCondition))
                {
                    if (!GridContainsColumn(ultraGrid, 0, strColumnCondition))
                    {
                        strMsg = "不存在条件字段【" + strColumnCondition + "】！";
                        return false;
                    }
                }

                if (string.IsNullOrEmpty(strOutColumn))
                {
                    strMsg = "未指定输出字段【" + strOutColumn + "】！";
                    return false;
                }

                if (!GridContainsColumn(ultraGrid, 0, strOutColumn))
                {
                    strMsg = "不存在输出字段【" + strOutColumn + "】！";
                    return false;
                }

                for (int i = 0; i < ultraGrid.Rows.Count; i++)
                {
                    if (!string.IsNullOrEmpty(strColumnCondition))
                    {
                        if (ultraGrid.Rows[i].Cells[strColumnCondition].Value.Equals(value))
                        {
                            if (ultraGrid.Rows[i].Cells["FCFLAG"].Value.ToString() != "校磅")
                                alistValue.Add(ultraGrid.Rows[i].Cells[strOutColumn].Value);
                        }
                    }
                    else
                    {
                        if (ultraGrid.Rows[i].Cells["FCFLAG"].Value.ToString() != "校磅")
                            alistValue.Add(ultraGrid.Rows[i].Cells[strOutColumn].Value);
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                strMsg = ex.Message;
                alistValue = null;
            }

            return false;
        }

        private static UltraGridExcelExporter ultraGridExcelExporter1 = new UltraGridExcelExporter();

        /// <summary>
        /// 判断系统是否安装EXCEL组件
        /// </summary>
        /// <returns></returns>
        public static bool ExcelInstalled()
        {
            bool bInstalled = (Type.GetTypeFromProgID("Excel.Application") != null);
            if (!bInstalled)
            {
                MessageBox.Show("系统没有安装EXCEL组件，无法导出数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            return bInstalled;
        }

        public static void ExportDataWithSaveDialog(ref UltraGrid ultraGrid1, string strFileName)
        {
            try
            {
                if (ultraGrid1.Rows.Count == 0) return;

                if (strFileName.Length == 0)
                    strFileName = "未命名";

                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Title = "保存";
                dlg.OverwritePrompt = true;
                dlg.Filter = "Excel文件(*.xls)|*.xls";
                dlg.AddExtension = true;
                dlg.FileName = strFileName;

                string strCaption = strFileName;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    strFileName = dlg.FileName;

                    Workbook wb = new Workbook();
                    Worksheet ws2 = wb.Worksheets.Add("Sheet1");
                    WorksheetMergedCellsRegion region = null;

                    ws2.Rows[0].Cells[0].Value = strCaption;

                    ws2.Rows[0].Cells[0].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
                    ws2.Rows[0].Cells[0].CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;
                    ws2.Rows[0].Cells[0].CellFormat.WrapText = Infragistics.Excel.ExcelDefaultableBoolean.True;
                    ws2.Rows[0].Cells[0].CellFormat.Font.Name = "宋体";
                    ws2.Rows[0].Cells[0].CellFormat.Font.Height = 350;
                    ws2.Rows[0].Cells[0].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                    ws2.Rows[0].Height = 880;

                    int iMaxY = 0;
                    int iMaxHeight = 0;
                    int iMaxWidth = 0;
                    for (int i = 0; i < ultraGrid1.DisplayLayout.Bands[0].Columns.Count; i++)
                    {
                        if (!ultraGrid1.DisplayLayout.Bands[0].Columns[i].Hidden && ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.LabelPosition != LabelPosition.None)
                        {
                            try
                            {
                                ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX].Value = ultraGrid1.DisplayLayout.Bands[0].Columns[i].Header.Caption;
                                ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
                                ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX].CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;
                                ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX].CellFormat.WrapText = Infragistics.Excel.ExcelDefaultableBoolean.True;
                                ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX].CellFormat.Font.Bold = Infragistics.Excel.ExcelDefaultableBoolean.True;
                                ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX].CellFormat.WrapText = Infragistics.Excel.ExcelDefaultableBoolean.True;
                                ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX].CellFormat.Font.Name = "宋体";

                                region = ws2.MergedCellsRegions.Add(1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY,
                                      ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX,
                                      1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY +
                                      ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanY - 1,
                                      ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX +
                                      ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanX - 1);

                                //region.CellFormat.FillPatternForegroundColor = Color.Lime;
                                //region.CellFormat.LeftBorderColor = region.CellFormat.RightBorderColor = region.CellFormat.TopBorderColor = region.CellFormat.BottomBorderColor = Color.DarkBlue;

                                if (ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Height != 500)
                                    ws2.Rows[1 + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Height = 500;

                                if (ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanY > iMaxHeight)
                                {
                                    iMaxHeight = ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanY;
                                }

                                if (ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY > iMaxY)
                                {
                                    iMaxY = ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY;
                                    iMaxHeight = iMaxY + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanY;
                                }

                                if (ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanX + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX > iMaxWidth)
                                {
                                    iMaxWidth = ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanX + ultraGrid1.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX;
                                }
                            }
                            catch (Exception ex) { string str = ex.Message; }
                        }
                    }

                    region = ws2.MergedCellsRegions.Add(0, 0, 0, iMaxWidth - 1);

                    //region.CellFormat.FillPatternForegroundColor = Color.Lime;
                    //region.CellFormat.LeftBorderColor = region.CellFormat.RightBorderColor = region.CellFormat.TopBorderColor = region.CellFormat.BottomBorderColor = Color.DarkBlue;

                    decimal dValue = 0.0M;
                    bool bDecimal = false;
                    for (int i = 0; i < ultraGrid1.Rows.Count; i++)
                    {
                        for (int j = 0; j < ultraGrid1.DisplayLayout.Bands[0].Columns.Count; j++)
                        {
                            try
                            {
                                if (!ultraGrid1.DisplayLayout.Bands[0].Columns[j].Hidden && ultraGrid1.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.LabelPosition != LabelPosition.LabelOnly)
                                {
                                    if (decimal.TryParse(Convert.ToString(ultraGrid1.Rows[i].Cells[j].Text), out dValue))
                                    {
                                        if (dValue == 0 || dValue < 1 || !Convert.ToString(ultraGrid1.Rows[i].Cells[j].Text).StartsWith("0"))
                                        {
                                            bDecimal = true;
                                        }
                                        else
                                        {
                                            bDecimal = false;
                                        }
                                    }
                                    else
                                    {
                                        bDecimal = false;
                                    }

                                    if (bDecimal)
                                    {
                                        ws2.Rows[1 + iMaxHeight + i].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX].Value = dValue;
                                    }
                                    else
                                    {
                                        ws2.Rows[1 + iMaxHeight + i].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX].Value = ultraGrid1.Rows[i].Cells[j].Text;
                                    }

                                    //if (ws2.Rows[1 + iMaxHeight + i].Height != 320)
                                    //    ws2.Rows[1 + iMaxHeight + i].Height = 320;

                                    //ws2.Rows[1 + iMaxHeight + i].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX].CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;

                                    //if (ultraGrid1.DisplayLayout.Bands[0].Columns[j].DataType == typeof(System.Decimal))
                                    //{
                                    //    ws2.Rows[1 + iMaxHeight + i].Cells[ultraGrid1.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Right;
                                    //}

                                    //region = ws2.MergedCellsRegions.Add(1 + iMaxHeight + i, ultraGrid1.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX,
                                    //    1 + iMaxHeight + i, ultraGrid1.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX);

                                    //region.CellFormat.LeftBorderColor = region.CellFormat.RightBorderColor = region.CellFormat.TopBorderColor = region.CellFormat.BottomBorderColor = Color.DarkBlue;
                                }
                            }
                            catch { }
                        }
                    }

                    wb.Save(strFileName);

                    if (File.Exists(strFileName) &&
                        MessageBox.Show("数据导出成功！\n需要打开所导出文件吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ProcessStartInfo p = new ProcessStartInfo(strFileName);
                        p.WorkingDirectory = Path.GetDirectoryName(strFileName);
                        Process.Start(p);
                    }
                }
            }
            catch { }
        }

        public static void ExportDataWithSaveDialog2(ref UltraGrid myGrid1, string strFileName)
        {
            try
            {
                if (myGrid1.Rows.Count == 0) return;
                if (strFileName.Length == 0) strFileName = "未命名";
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Title = "保存";
                dlg.OverwritePrompt = true;
                dlg.Filter = "Excel文件(*.xls)|*.xls";
                dlg.AddExtension = true;
                dlg.FileName = strFileName;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    strFileName = dlg.FileName;
                    ultraGridExcelExporter1.Export(myGrid1, strFileName);

                    //if (MessageBox.Show("数据导出成功！\n需要打开所导出文件吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    //{
                    //    ProcessStartInfo p = new ProcessStartInfo(strFileName);
                    //    p.WorkingDirectory = Path.GetDirectoryName(strFileName);
                    //    Process.Start(p);
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public static bool IPCheck(string IP)
        {
            string Segment = @"(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)";
            return Regex.IsMatch(IP, ("^" + Segment + @"\." + Segment + @"\." + Segment + @"\." + Segment + "$"));
        }

        public static bool Pinging(string IP)
        {
            try
            {
                Ping ping = new Ping();
                PingOptions options = new PingOptions();
                options.DontFragment = true;
                byte[] buffer = Encoding.ASCII.GetBytes("TEST PING");
                PingReply reply = ping.Send(IP, 3000, buffer, options);

                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
            }
            catch { }

            return false;
        }

        public static bool PrinterExists(string strPrinterName)
        {
            if (string.IsNullOrEmpty(strPrinterName))
                return false;

            foreach (string printerName in PrinterSettings.InstalledPrinters)
            {
                if (strPrinterName.Equals(printerName))
                    return true;
            }
            return false;
        }

        public static bool FontFamilyNameExists(string strFontFamilyName)
        {
            if (string.IsNullOrEmpty(strFontFamilyName))
                return false;

            foreach (FontFamily fontfamily in FontFamily.Families)
            {
                if (strFontFamilyName.Equals(fontfamily.Name))
                    return true;
            }
            return false;
        }

        public static void ResetHashtable(ref Hashtable htbl)
        {
            if (htbl == null)
                htbl = new Hashtable();
            else
                htbl.Clear();
        }

        public static void ResetArraylist(ref ArrayList alist)
        {
            if (alist == null)
                alist = new ArrayList();
            else
                alist.Clear();
        }

        public static bool CheckComboBoxSelection(UltraComboEditor cbEdit, string Caption, bool MustSelect, bool ShowError, out string Message)
        {
            Message = "";
            try
            {
                if (cbEdit != null)
                {
                    if (MustSelect)
                    {
                        if (cbEdit.SelectedIndex < 0)
                        {
                            Message = cbEdit.Text.Trim().Length > 0 ? Caption + "不正确，请从列表中选取！" : "请选择" + Caption + "！";
                            if (ShowError)
                                MessageBox.Show(Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            return false;
                        }
                    }
                    else
                    {
                        if (cbEdit.SelectedIndex < 0 && cbEdit.Text.Trim().Length > 0)
                        {
                            Message = Caption + "不正确，请从列表中选取！";
                            if (ShowError)
                                MessageBox.Show(Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            return false;
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Message = Caption + "验证出错！\n" + ex.Message;
                if (ShowError)
                    MessageBox.Show(Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return false;
            }
        }

        #region 窗体及控件样式

        private static Color _BACKCOLOR = Color.FromArgb(202, 222, 247);

        private static void SetControlAppearance(Control ctrl)
        {
            try
            {
                if (ctrl.GetType().IsSubclassOf(typeof(Form)))
                    ctrl.BackColor = _BACKCOLOR;
                else if (ctrl.GetType().Equals(typeof(Panel)))
                {
                    ctrl.BackColor = _BACKCOLOR;
                    ((Panel)ctrl).BorderStyle = BorderStyle.None;
                }
                else if (ctrl.GetType().Equals(typeof(PictureBox)))
                {
                    ctrl.BackColor = _BACKCOLOR;
                    ((PictureBox)ctrl).BorderStyle = BorderStyle.None;
                }
                else if (ctrl.GetType().Equals(typeof(GroupBox)))
                    ctrl.BackColor = _BACKCOLOR;
                else if (ctrl.GetType().Equals(typeof(ToolStrip)))
                    ctrl.BackColor = _BACKCOLOR;
                else if (ctrl.GetType().IsSubclassOf(typeof(Label)))
                    ctrl.BackColor = _BACKCOLOR;
                else if (ctrl.GetType().IsSubclassOf(typeof(TextBoxBase)))
                    ctrl.BackColor = SystemColors.Window;
                else if (ctrl.GetType().IsSubclassOf(typeof(UserControl)))
                    ctrl.BackColor = _BACKCOLOR;

                if (ctrl.GetType().IsSubclassOf(typeof(ControlBase)) && !ctrl.GetType().IsSubclassOf(typeof(EditorButtonControlBase)))
                    ((ControlBase)ctrl).Appearance.BackColor = _BACKCOLOR;
                else if (ctrl.GetType().Equals(typeof(UltraGroupBox)) || ctrl.GetType().IsSubclassOf(typeof(UltraGroupBox)))
                {
                    ((UltraGroupBox)ctrl).ViewStyle = GroupBoxViewStyle.Office2007;
                    ((UltraGroupBox)ctrl).HeaderBorderStyle = UIElementBorderStyle.Etched;
                    ((UltraGroupBox)ctrl).BorderStyle = GroupBoxBorderStyle.None;
                    ((UltraGroupBox)ctrl).Appearance.BackColor = _BACKCOLOR;
                    ((UltraGroupBox)ctrl).Appearance.BackColor2 = _BACKCOLOR;
                    ((UltraGroupBox)ctrl).HeaderAppearance.BackColor = Color.FromArgb(183, 208, 250);
                    ((UltraGroupBox)ctrl).HeaderAppearance.BackColor2 = Color.FromArgb(183, 208, 250);
                    ((UltraGroupBox)ctrl).ContentAreaAppearance.BackColor = Color.FromArgb(218, 232, 248);
                    ((UltraGroupBox)ctrl).ContentAreaAppearance.BackColor2 = Color.FromArgb(218, 232, 248);
                }
                else if (ctrl.GetType().Equals(typeof(UltraPanel)) || ctrl.GetType().IsSubclassOf(typeof(UltraPanel)))
                {
                    ((UltraPanel)ctrl).Appearance.BackColor = _BACKCOLOR;
                    ((UltraPanel)ctrl).Appearance.BackColor2 = _BACKCOLOR;
                    ((UltraPanel)ctrl).Appearance.BorderColor = Color.DarkGray;
                    ((UltraPanel)ctrl).BorderStyle = UIElementBorderStyle.Etched;
                }
                else if (ctrl.GetType().Equals(typeof(UltraTabControl)))
                {
                    ((UltraTabControl)ctrl).ViewStyle = Infragistics.Win.UltraWinTabControl.ViewStyle.Office2007;
                }
            }
            catch { }
        }

        public static void SetControlStyle(Control parentCtrl)
        {
            try
            {
                SetControlAppearance(parentCtrl);
                foreach (Control ctrl in parentCtrl.Controls)
                {
                    if (ctrl is UserControl)
                        continue;
                    SetControlStyle(ctrl);
                }
            }
            catch { }
        }

        #endregion 窗体及控件样式

        public static void SetUltraGridColumnColor(ValueList colorList, string columnName, UltraGrid ultraGrid1)
        {
            try
            {
                Infragistics.Win.Appearance apprc;
                OperatorCondition oc;
                ConditionValueAppearance cva = new ConditionValueAppearance();

                for (int i = 0; i < colorList.ValueListItems.Count; i++)
                {
                    apprc = new Infragistics.Win.Appearance();
                    if (i == 0)
                        apprc.BackColor = Color.Cornsilk;
                    else if (i == 1)
                        apprc.BackColor = Color.Gainsboro;
                    else if (i == 2)
                        apprc.BackColor = Color.LightSkyBlue;
                    else if (i == 3)
                        apprc.BackColor = Color.PaleGreen;
                    else if (i == 4)
                        apprc.BackColor = Color.Lime;
                    oc = new OperatorCondition(ConditionOperator.Equals, colorList.ValueListItems[0].DisplayText, false, typeof(string));
                    cva.Add((ICondition)oc, apprc);
                }

                ultraGrid1.DisplayLayout.Bands[0].Columns[columnName].ValueBasedAppearance = cva;
            }
            catch { }
        }

        public static void SetStaticsInfoCount(ref UltraGrid myGrid1, ArrayList alistColumns, bool clearExists)
        {
            try
            {
                UltraGridBand band = myGrid1.DisplayLayout.Bands[0];
                if (clearExists)
                    band.Summaries.Clear();
                band.Override.SummaryFooterCaptionVisible = Infragistics.Win.DefaultableBoolean.False;

                for (int i = 0; i < alistColumns.Count; i++)
                {
                    try
                    {
                        SummarySettings summary = band.Summaries.Add(SummaryType.Count, band.Columns[alistColumns[i].ToString()]);
                        summary.SummaryDisplayArea = SummaryDisplayAreas.BottomFixed;
                        summary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
                        summary.DisplayFormat = "{0}";

                        summary.Appearance.TextHAlign = Infragistics.Win.HAlign.Right;
                        summary.Appearance.TextVAlign = Infragistics.Win.VAlign.Middle;
                        summary.Appearance.FontData.Bold = DefaultableBoolean.True;
                    }
                    catch { }
                }
            }
            catch { }
        }

        public static void SetStaticsInfoSum(ref UltraGrid myGrid1, ArrayList alistColumns, bool clearExists)
        {
            try
            {
                UltraGridBand band = myGrid1.DisplayLayout.Bands[0];
                if (clearExists)
                    band.Summaries.Clear();
                band.Override.SummaryFooterCaptionVisible = Infragistics.Win.DefaultableBoolean.False;

                for (int i = 0; i < alistColumns.Count; i++)
                {
                    try
                    {
                        SummarySettings summary = band.Summaries.Add(SummaryType.Sum, band.Columns[alistColumns[i].ToString()]);
                        summary.SummaryDisplayArea = SummaryDisplayAreas.BottomFixed;
                        summary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
                        summary.DisplayFormat = "{0}";

                        summary.Appearance.TextHAlign = Infragistics.Win.HAlign.Right;
                        summary.Appearance.TextVAlign = Infragistics.Win.VAlign.Middle;
                        summary.Appearance.FontData.Bold = DefaultableBoolean.True;
                    }
                    catch { }
                }
            }
            catch { }
        }

        public static void ClearUltraGridColumnsSort(UltraGrid ultraGrid)
        {
            if (ultraGrid != null)
            {
                foreach (UltraGridBand band in ultraGrid.DisplayLayout.Bands)
                {
                    foreach (UltraGridColumn col in band.Columns)
                    {
                        if (col.SortIndicator == SortIndicator.Disabled)
                            continue;
                        col.SortIndicator = SortIndicator.None;
                    }
                }
            }
        }

        public static DataTable ConvertToDataTable(IList list)
        {
            DataTable table = new DataTable();
            if ((list != null) && (list.Count > 0))
            {
                Hashtable hashtable2;
                Hashtable hashtable = (Hashtable)list[0];
                foreach (DictionaryEntry entry in hashtable)
                {
                    string columnName = entry.Key.ToString();
                    if (entry.Value == null)
                    {
                        table.Columns.Add(columnName, typeof(string));
                    }
                    else if ((entry.Value != null) && typeof(Hashtable).Equals(entry.Value.GetType()))
                    {
                        hashtable2 = (Hashtable)entry.Value;
                        table.Columns.Add(columnName, hashtable2["value"].GetType());
                    }
                    else
                    {
                        table.Columns.Add(columnName, entry.Value.GetType());
                    }
                }
                for (int i = 0; i < list.Count; i++)
                {
                    hashtable = (Hashtable)list[i];
                    ArrayList list2 = new ArrayList();
                    foreach (DictionaryEntry entry in hashtable)
                    {
                        if ((entry.Value != null) && typeof(Hashtable).Equals(entry.Value.GetType()))
                        {
                            hashtable2 = (Hashtable)entry.Value;
                            list2.Add(hashtable2["value"]);
                        }
                        else
                        {
                            list2.Add(entry.Value);
                        }
                    }
                    table.LoadDataRow(list2.ToArray(), true);
                }
            }
            return table;
        }


        /// <summary>
        /// 冻结行
        /// </summary>
        /// <param name="ultraGrid1"></param>
        /// <param name="column"></param>
        public static void UseFixedHeader(UltraGrid ultraGrid1, string column)
        {
            ultraGrid1.DisplayLayout.UseFixedHeaders = true;
            ultraGrid1.DisplayLayout.Bands[0].Columns[column].Header.Fixed = true;
            ultraGrid1.DisplayLayout.Bands[0].Columns[column].Header.FixOnRight = DefaultableBoolean.True;
            ultraGrid1.DisplayLayout.Bands[0].Columns[column].Header.FixedHeaderIndicator = FixedHeaderIndicator.None;
            ultraGrid1.DisplayLayout.Override.FixedHeaderAppearance.BackColor = Color.LightYellow;
            ultraGrid1.DisplayLayout.Override.FixedCellAppearance.BackColor = Color.LightYellow;
            ultraGrid1.DisplayLayout.Override.FixedCellSeparatorColor = Color.Red;
        }

        /// <summary>
        /// 设置ultraGrid为不可编辑,如有选择Checked列Key为selectkey
        /// </summary>
        /// <param name="ulgrid">ultraGrid控件</param>
        public static void SetNoEnable(params Infragistics.Win.UltraWinGrid.UltraGrid[] ulgrids)
        {
            try
            {
                foreach (var ulgrid in ulgrids)
                {
                    foreach (Infragistics.Win.UltraWinGrid.UltraGridBand band in ulgrid.DisplayLayout.Bands)
                    {
                        band.Override.CellClickAction = CellClickAction.EditAndSelectText;//选中整行
                        foreach (Infragistics.Win.UltraWinGrid.UltraGridColumn Col in band.Columns)
                        {
                            Col.CellClickAction = CellClickAction.EditAndSelectText;
                            if (Col.Style != Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox && Col.Key.ToLower() != "selectkey" && Col.Key.ToLower() != "check" && Col.Key.ToLower() != "isselect" && Col.Key.ToLower() != "checkbox")//选择复选框
                            {
                                if ((Col.Tag + "") == "AllowEdit") continue;
                                Col.CellActivation = Infragistics.Win.UltraWinGrid.Activation.ActivateOnly;
                                //Col.SortIndicator = SortIndicator.Disabled;//不可以排序；会导致抬头变两行
                                if (Col.DataType == typeof(DateTime?))
                                {
                                    Col.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DateTime;
                                }
                            }
                            else
                            {
                                Col.CellClickAction = CellClickAction.Edit;
                                Col.CellActivation = Infragistics.Win.UltraWinGrid.Activation.AllowEdit;
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 设置ultraGrid为不可编辑,strKey为例外可以编辑的列
        /// </summary>
        /// <param name="ulgrid">ultraGrid控件</param>
        public static void SetNoEnable(UltraGrid ulgrid, List<string> strkey)
        {
            try
            {
                foreach (Infragistics.Win.UltraWinGrid.UltraGridBand band in ulgrid.DisplayLayout.Bands)
                {
                    band.Override.CellClickAction = CellClickAction.EditAndSelectText;//选中整行
                    foreach (Infragistics.Win.UltraWinGrid.UltraGridColumn Col in band.Columns)
                    {
                        Col.CellClickAction = CellClickAction.EditAndSelectText;
                        if (Col.Style != Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox && !strkey.Exists(s => s.ToLower() == Col.Key.ToLower()))//选择复选框
                        {
                            Col.CellActivation = Infragistics.Win.UltraWinGrid.Activation.ActivateOnly;
                            //Col.SortIndicator = SortIndicator.Disabled;//不可以排序；会导致抬头变两行
                            if (Col.DataType == typeof(DateTime?))
                            {
                                Col.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DateTime;
                            }
                        }
                        else
                        {
                            Col.CellClickAction = CellClickAction.Edit;
                            Col.CellActivation = Infragistics.Win.UltraWinGrid.Activation.AllowEdit;
                        }
                    }
                }
            }
            catch
            {
            }
        }

        public static void ShowGridCaption<T>(UltraGridBand gridBand)
        {
            try
            {
                PropertyInfo[] propertyInfos = typeof(T).GetProperties();
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    if (gridBand.Columns.Exists(propertyInfo.Name))
                    {
                        //设置单元格为空时的值。
                        if (propertyInfo.PropertyType == typeof(string))
                        {
                            gridBand.Columns[propertyInfo.Name].Nullable = Infragistics.Win.UltraWinGrid.Nullable.EmptyString;
                        }

                        object[] desAttributes = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (desAttributes.Length > 0)
                        {
                            gridBand.Columns[propertyInfo.Name].Header.Caption = ((DescriptionAttribute)desAttributes[0]).Description;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}