using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using DevExpress.XtraEditors; using System.Drawing; using DevExpress.XtraGrid.Views.Grid; using System.Windows.Forms; using System.Data; using DevExpress.XtraGrid.Columns; using Lskj.Business.Impl; using Lskj.Control.Model; using System.Threading; using Lskj.Util; using System.Text.RegularExpressions; using Lskj.Data; using DevExpress.XtraGrid.Menu; using DevExpress.Utils.Menu; using System.Data.SqlClient; using Lskj.Business; using Lskj.Model; using Lskj.Core; namespace Lskj.Control { public partial class AutoGridRevLookUp : TextEdit { /// /// 是否能直接弹出框 /// private bool PopShowFlag = true; /// /// 是否处理过计算 /// private bool _Handed; /// /// 弹出框最大宽度 /// private int _maxPopupWidth = 800; private string _value; private bool _hasRemark = false; /// /// 后台线程是否在执行中 /// private bool _working = false; private List _queryQueue = new List(); /// /// The _popup /// public AutoGridRevPopup _popup = null; /// /// 新增模糊查询条件 /// private string AddConditions = string.Empty; /// /// 弹出框是否显示 /// /// true if this instance is show popup; otherwise, false. public bool IsShowPopup; /// /// 弹出框是否自动弹出 /// /// true if this instance is show popup; otherwise, false. public bool AutoShowPopup = true; /// /// 是否需要自动匹配列宽度 /// [Description("是否需要自动匹配列宽度")] public bool IsBestFitColumns = true; /// /// The minimum popup width /// [Description("弹出框最小宽度")] public int MinPopupWidth; /// /// The minimum popup height /// [Description("弹出框最小高度")] public int MinPopupHeight; /// /// The value field /// public string ValueField = string.Empty; /// /// The value member /// [Description("设置ValueMember")] public string ValueMember = string.Empty; /// /// The text field /// [Description("设置TextMember")] public string TextMember = string.Empty; public string FormKey = string.Empty; /// /// The remark text /// [Description("设置备注")] public string RemarkField = "remark"; /// /// 数据源 /// public string SourceSQL = string.Empty; /// /// The contro object /// public MyControl ControlObj; /// /// 控件对象 /// public ControlModel Model; /// /// 隐藏值改变时触发 /// public event EventHandler HiddenValueChange; /// /// 是否为回车或下键显示弹出框 /// private bool IsKeyDownFocusd = false; /// /// 是否已经赋予数据源 /// public bool IsSetDataSource = false; /// /// 搜索回调 /// public event EventHandler OnSearchCallBack; /// /// 隐藏值 /// /// The value. public new string EditValue { get { return _value; } set { bool TriggerCorrelation = (this._value != value); if (this.Model != null && (this.Model.FieldType == ControlType.LabAutoCompleteText || this.Model.FieldType == ControlType.LabAutoCompleteTextParam)) { // 自动搜索框显示名称、自动搜索框显示名称带参数时,直接显示与保存值,此时值可以任意输入,无需匹配数据源. this.Text = this._value = value; } else { if (this.DataSource != null && this.DataSource is DataTable) { DataTable table = this.DataSourceTable != null && this.DataSourceTable.Rows.Count > 0 && !SourceSQL.ToLower().StartsWith("exec") ? this.DataSourceTable : this.DataSource as DataTable; DataRow rowItem = table.Select("1=1").FirstOrDefault(x => value == x[ValueMember] + ""); if (rowItem != null) { this._value = rowItem[ValueMember] + ""; this.Text = rowItem[TextMember] + ""; this.SelectionStart = this.Text.Length; } else { rowItem = (this.DataSource as DataTable).Select("1=1").FirstOrDefault(x => value == x[TextMember] + ""); if (rowItem != null) { this._value = rowItem[ValueMember] + ""; this.Text = rowItem[TextMember] + ""; this.SelectionStart = this.Text.Length; } else { DataTable refTable = BaseImpl.GetDataTableResult(SourceSQL); this.DataSource = refTable; this.DataSourceTable = refTable.Copy(); DataTable newTable = this.DataSourceTable != null && this.DataSourceTable.Rows.Count > 0 && !SourceSQL.ToLower().StartsWith("exec") ? this.DataSourceTable : this.DataSource as DataTable; DataRow newRowItem = newTable.Select("1=1").FirstOrDefault(x => value == x[ValueMember] + ""); if (newRowItem != null) { this._value = newRowItem[ValueMember] + ""; this.Text = newRowItem[TextMember] + ""; this.SelectionStart = this.Text.Length; } else { newRowItem = (this.DataSource as DataTable).Select("1=1").FirstOrDefault(x => value == x[TextMember] + ""); if (newRowItem != null) { this._value = newRowItem[ValueMember] + ""; this.Text = newRowItem[TextMember] + ""; this.SelectionStart = this.Text.Length; } else { this._value = string.Empty; this.Text = string.Empty; } } } } } else { this._value = string.Empty; this.Text = string.Empty; } } if (TriggerCorrelation && this.Model != null && (this.Model.FieldType == ControlType.LabAutoCompleteValue || this.Model.FieldType == ControlType.LabAutoCompleteValueParam || this.Model.FieldType == ControlType.LabAutoCompleteText || this.Model.FieldType == ControlType.LabAutoCompleteTextParam)) { //隐藏值改变后触发关联 if (HiddenValueChange != null) HiddenValueChange(this, null); } } } /// /// 设置数据源 /// /// The data source. public object DataSource { get { return this._popup != null ? this._popup.GridControlObj.DataSource : null; } set { if (value != null) { this._popup.GridControlObj.DataSource = value; this._popup.GridViewObj.PopupMenuShowing += new PopupMenuShowingEventHandler(this.OnGridViewPopupMenuShowing); this._popup.Model = Model; this.SetGridViewColumns(value as DataTable); } } } /// /// 数据源(用于匹配数据) /// public DataTable DataSourceTable; public string SpeciesValue; /// /// 说明:隐藏弹出框 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public void HidePopup() { if (this._popup != null)//this.IsShowPopup && this._popup != null { this.IsShowPopup = false; this._popup.Hide(); } } /// /// 说明:显示弹出框 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public void ShowPopup() { try { if (this.InvokeRequired) { this.Invoke(new Action(() => { if (!this.Properties.ReadOnly && this.Enabled)//!this.Properties.ReadOnly && this.Enabled && !this.IsShowPopup { if (AutoShowPopup && this._popup != null) { CalcPopupLocation(); this.IsShowPopup = true; this._popup.Show(); } } })); } else { if (!this.Properties.ReadOnly && this.Enabled)//!this.Properties.ReadOnly && this.Enabled && !this.IsShowPopup { if (AutoShowPopup && this._popup != null) { CalcPopupLocation(); this.IsShowPopup = true; this._popup.Show(); } } } } catch (Exception) { } } /// /// 弹出框 /// /// The popup. [Description("自动搜索弹出框")] public AutoGridRevPopup Popup { get { return this._popup; } private set { _popup = value; } } /// /// 界面关闭时 /// public event EventHandler OnPopupClosed; public AutoGridRevLookUp() { InitializePopup(); InitializeEvent(); this.Disposed += OnDisposed; } /// /// 说明:初始化事件 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void InitializeEvent() { this.GotFocus += new EventHandler(OnAutoGridLookUpGotFocus); this.Click += new EventHandler(OnAutoGridRevLookUpMouseClick); this.LostFocus += new EventHandler(OnAutoGridLookUpLostFocus); this.KeyUp += new KeyEventHandler(OnAutoGridLookUpKeyUp); this.TextChanged += AutoGridLookUp_TextChanged; //this.Leave += new EventHandler(OnAutoGridLookUpLostFocus); this._popup.GridControlObj.LostFocus += new EventHandler(OnAutoGridLookUpLostFocus); this._popup.OnGridViewMouseClick += new EventHandler(OnPopupGridViewMouseClick); this._popup.OnGridViewEnter += new KeyEventHandler(OnPopupGridViewEnter); } /// /// 说明:初始化弹出框 /// 创建人:龚宇超 /// 创建日期:2018-03-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void InitializePopup() { this._popup = new AutoGridRevPopup(); this._popup.LookUp = this; this._popup.Hide(); } private void CalcFormAndGrid() { Thread queryThread = new Thread(CalcPopupSize); queryThread.IsBackground = true; queryThread.Start(Popup); } /// /// 说明:计算弹出控件位置 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void CalcPopupLocation() { this._popup.Parent = this.GetParent(this.Parent); Form form = this._popup.Parent as Form; if (form != null) { int iTop = this.Top + this.Height; int iLeft = this.Left; System.Windows.Forms.Control ctr = this.Parent; while (ctr != form) { iTop += ctr.Top; iLeft += ctr.Left; ctr = ctr.Parent; } if (iTop + this.Height + this._popup.Height > ctr.Height) { if (iTop - this.Height > ctr.Height - iTop) { if (this._popup.Height > iTop - this.Height) { this._popup.Height = iTop - this.Height; iTop = 0; } else { iTop = iTop - this.Height - this._popup.Height; } } else { this._popup.Height = ctr.Height - iTop - 30; } } if (iLeft + this._popup.Width > ctr.Width) { if (iLeft + this.Width > ctr.Width - iLeft) { if (this._popup.Width > iLeft + this.Width) { this._popup.Width = iLeft + this.Width; iLeft = 0; } else iLeft = iLeft + this.Width - this._popup.Width; } else this._popup.Width = ctr.Width - iLeft - 30; } this._popup.Left = iLeft; this._popup.Top = iTop; } this._popup.BringToFront(); } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2018-03-21 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void HandPopupSqlValue(object searchText) { if (!string.IsNullOrEmpty(SourceSQL)) { string sqlValue = string.Empty; if (SourceSQL.ToLower().StartsWith("exec")) { // 存储过程处理 sqlValue = SourceSQL; if (sqlValue.Contains("{" + ValueField + "}")) sqlValue = sqlValue.Replace("{" + ValueField + "}", searchText + ""); if (sqlValue.Contains("{" + TextMember + "}")) sqlValue = sqlValue.Replace("{" + TextMember + "}", searchText + ""); if (sqlValue.Contains("{" + RemarkField + "}")) sqlValue = sqlValue.Replace("{" + RemarkField + "}", searchText + ""); if (this.ControlObj != null) sqlValue = this.ControlObj.ReplaceControlValue(sqlValue); sqlValue = ProcessingSql(sqlValue); sqlValue = MainImpl.GetDefaultValue(SourceSQL); sqlValue = ReplaceHelper.ReplaceParam(SourceSQL); } else { // SQL处理 string remarkCond = string.Empty; bool nonEnglish = false;//是否全是英文 if (IsChina(searchText + "") || IsNumberic(searchText + "")) { nonEnglish = true; } if (this._hasRemark) { if (nonEnglish) { remarkCond = string.Format(" or {0} like '%{1}%' ", RemarkField, (searchText + "").Replace("[", "[[]")); } else { remarkCond = string.Format(" or {0} like '%{1}%' or dbo.P_getpy({0}) like '%{1}%'", RemarkField, (searchText + "").Replace("[", "[[]")); } } //SourceSQL = ProcessingSql(SourceSQL); //SourceSQL = MainImpl.GetDefaultValue(SourceSQL); //SourceSQL = ReplaceHelper.ReplaceParam(SourceSQL);//同类似方法 if (nonEnglish) { string sql = "select top 500 * from ({0}) temp where {1} like '%{3}%' or {2} like '%{3}%' "; sqlValue = string.Format(sql + remarkCond + AddConditions, SourceSQL, ValueField, TextMember, (searchText + "").Replace("[", "[[]")); } else { string sql = "select top 500 * from ({0}) temp where {1} like '%{3}%' or {2} like '%{3}%' or dbo.P_getpy({2}) like '%{3}%' "; sqlValue = string.Format(sql + remarkCond + AddConditions, SourceSQL, ValueField, TextMember, (searchText + "").Replace("[", "[[]")); } if (Model != null && !string.IsNullOrEmpty(Model.AddOrderByCond)) { sqlValue = string.Format("{0} {1}", sqlValue, Model.AddOrderByCond); } sqlValue = MainImpl.GetDefaultValue(sqlValue); } //带参数sql,处理 if (this.ControlObj != null && Regex.IsMatch(SourceSQL, ReplaceHelper.ReplaceParamKey)) { string sourceSql = sqlValue; // Step 1:替换SpeciesNo List condition = ReplaceHelper.GetParamFields(sourceSql); if (!string.IsNullOrEmpty(SpeciesValue)) { foreach (string item in condition) { string field = item.Replace("{", "").Replace("}", ""); if ("speciesno".Equals(field, StringComparison.OrdinalIgnoreCase)) { sourceSql = sourceSql.Replace(item, SpeciesValue); } } } // Step 2:替换SpeciesNo if (this.ControlObj.CurrentData != null && this.ControlObj.CurrentData.Table.Columns.Contains("SpeciesNo")) { foreach (string item in condition) { string field = item.Replace("{", "").Replace("}", ""); if ("speciesno".Equals(field, StringComparison.OrdinalIgnoreCase)) { sourceSql = sourceSql.Replace(item, this.ControlObj.CurrentData["SpeciesNo"] + ""); } } } sqlValue = ControlObj.ReplaceControlValue(sourceSql.Replace("#", "")); } if (!this._working) { Thread thread = new Thread(new ParameterizedThreadStart(RefreshPopupDataSource)); thread.IsBackground = true; thread.Start(sqlValue); } else { this._queryQueue.Add(sqlValue); } } } /// /// 处理sql /// /// /// private string ProcessingSql(string sqlValue) { // 带参数sql,处理 if (this.ControlObj != null && Regex.IsMatch(SourceSQL, ReplaceHelper.ReplaceParamKey)) { string sourceSql = sqlValue; // Step 1:替换SpeciesNo List condition = ReplaceHelper.GetParamFields(sourceSql); if (!string.IsNullOrEmpty(SpeciesValue)) { foreach (string item in condition) { string field = item.Replace("{", "").Replace("}", ""); if ("speciesno".Equals(field, StringComparison.OrdinalIgnoreCase)) { sourceSql = sourceSql.Replace(item, SpeciesValue); } } } // Step 2:替换SpeciesNo if (this.ControlObj.CurrentData != null && this.ControlObj.CurrentData.Table.Columns.Contains("SpeciesNo")) { foreach (string item in condition) { string field = item.Replace("{", "").Replace("}", ""); if ("speciesno".Equals(field, StringComparison.OrdinalIgnoreCase)) { sourceSql = sourceSql.Replace(item, this.ControlObj.CurrentData["SpeciesNo"] + ""); } } } sqlValue = ControlObj.ReplaceControlValue(sourceSql.Replace("#", "")); } return sqlValue; } /// /// 说明:刷新弹出框数据 /// 创建人:龚宇超 /// 创建日期:2018-05-02 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The SQL value. private void RefreshPopupDataSource(object sqlValue) { try { if (this.InvokeRequired) { this.Invoke(new EventHandler(delegate { this._working = true; this.Popup.LabelObj.Text = "正在筛选数据,请稍后..."; this.Popup.BottomPanelObj.Visible = true; this.Popup.GridControlObj.DataSourceTable().Clear(); })); } DateTime beginTime = DateTime.Now; //DataTable table = MainImpl.GetDataTableResult(sqlValue + ""); DataTable table = new DataTable(); if (!string.IsNullOrWhiteSpace(sqlValue + "")) { try { table = SqlHelper.ExecuteDataTable(sqlValue + ""); } catch (Exception) { table = new DataTable(); } } DateTime endTime = DateTime.Now; if (this._queryQueue.Count > 0) { string sql = MainImpl.GetDefaultValue(this._queryQueue.Last()); sql = ReplaceHelper.ReplaceParam(sql); // 在检索过程中还存在输入数据,则拿最后一次数据在进行匹配一次 Thread thread = new Thread(new ParameterizedThreadStart(RefreshPopupDataSource)); thread.IsBackground = true; thread.Start(sql); this._queryQueue.Clear(); } else { if (this.InvokeRequired) { this.Invoke(new EventHandler(delegate { int second = Convert.ToInt32((endTime - beginTime).TotalSeconds); string tipMsg = "数据筛选完成."; this.Popup.LabelObj.Text = second > 0 ? string.Format(tipMsg + "(耗时{0}秒)", second) : tipMsg; this.Popup.GridControlObj.DataSource = table; this._working = false; this.CalcFormAndGrid(); })); } } } catch (Exception ex) { } } /// /// 说明:获取顶层窗口 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// Control. private Form GetParent(System.Windows.Forms.Control ctr) { if (ctr == null) return null; return ctr is Form ? ctr as Form : GetParent(ctr.Parent); } /// /// 说明:设置值 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void SetValue() { DataRow rowItem = this._popup.GridViewObj.GetFocusedDataRow(); if (rowItem != null) { this.EditValue = rowItem[ValueMember] + ""; //this.Focus(); } if (this.OnPopupClosed != null) this.OnPopupClosed(this, null); } /// /// 说明:根据输入值判断下拉框中是否存在value值 /// 创建人:王一帆 /// 创建日期:2020-05-14 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public string getValueItem(string ItemText) { string obj = string.Empty; DataTable table = this.DataSourceTable; DataTable currtable = this.DataSource as DataTable; if (table != null) { DataRow rowItemValue = table.Rows.Cast().FirstOrDefault(x => x[Model.TextMember] + "" == ItemText); obj = rowItemValue != null ? rowItemValue[Model.ValueMember] + "" : string.Empty; } if (string.IsNullOrEmpty(obj) && currtable != null) { DataRow rowItemValue = currtable.Rows.Cast().FirstOrDefault(x => x[Model.TextMember] + "" == ItemText); obj = rowItemValue != null ? rowItemValue[Model.ValueMember] + "" : string.Empty; } return obj; } /// /// 说明:设置自定义列 /// 创建人:王一帆 /// 创建日期:2019-09-17 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public virtual void SetCustomColumns() { if (string.IsNullOrEmpty(this.FormKey) || !BaseImpl.HasExistsTable(ResourceKeys.SettingTableName)) return; DataTable customTable = this._popup.GridViewObj.GetCustomColumnByDatabase(this.FormKey); if (customTable != null && customTable.Rows.Count > 0) { foreach (DataRow rowItem in customTable.Rows) { string fieldName = rowItem["fieldName"] + ""; int fieldWidth = Convert.ToInt32(rowItem["fieldWidth"]); int index = Convert.ToInt32(rowItem["orderid"]); bool visible = "1".Equals(rowItem["isVisible"] + "") && fieldWidth > 0; bool isFix = "True".Equals(rowItem["IfFixColumn"] + "", StringComparison.OrdinalIgnoreCase); GridColumn gridColumn = this._popup.GridViewObj.Columns.ColumnByName(fieldName); if (gridColumn != null && gridColumn.Visible && gridColumn.Width > 0) { GridColumn colObj = this._popup.GridViewObj.Columns[fieldName]; colObj.VisibleIndex = index; colObj.Width = fieldWidth; colObj.Visible = visible; colObj.Fixed = isFix ? FixedStyle.Left : FixedStyle.None; } } } } /// /// 说明:重置表格属性 /// 创建人:王一帆 /// 创建日期:2019-09-17 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected virtual void ResetItemClick(object sender, EventArgs e) { if (!BaseImpl.HasExistsTable(ResourceKeys.SettingTableName)) { MessageUtil.Show(ResourceKeys.NotFoundSettingColumnTable); return; } if (MessageUtil.Show(ResourceKeys.IsResetColumn, MessageBoxButtons.YesNo) == DialogResult.Yes) { bool success = this._popup.GridViewObj.ResetCustomColumnToDatabase(FormKey); SetGridViewColumns(DataSource as DataTable); _Handed = false; this.CalcFormAndGrid(); MessageUtil.Show(success ? ResourceKeys.ResetSuccess : ResourceKeys.ResetFault); this.ShowPopup(); } } /// /// 说明:保存表格属性 /// 创建人:王一帆 /// 创建日期:2019-09-17 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected virtual void SaveItemClick(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.FormKey)) { MessageUtil.Show(ResourceKeys.NotSettingResetColumn); return; } DataRow rowItem = null; bool success = BaseImpl.HasExistsDataRow(ResourceKeys.SettingTableName, "formKey", FormKey, string.Format(" and OperatorId='{0}' ", ERPInfo.Instance.UserId), out rowItem); if (!success) { MessageUtil.Show(ResourceKeys.NotFoundSettingColumnTable); return; } if (MessageUtil.Show(ResourceKeys.IsSaveColumn, MessageBoxButtons.YesNo) == DialogResult.Yes) { try { if (rowItem == null) { success = this._popup.GridViewObj.SaveCustomColumnToDatabase(this.FormKey); } else { success = this._popup.GridViewObj.UpdateCustomColumnToDatabase(this.FormKey); } MessageUtil.Show(success ? ResourceKeys.SaveSuccess : ResourceKeys.SaveFault); } catch (SqlException sex) { if (sex.Message.Contains(ResourceKeys.FieldLenIsShort) && MessageUtil.Show(ResourceKeys.SaveFault + "\r\n" + ResourceKeys.CanUpgradeTable, MessageBoxButtons.YesNo) == DialogResult.Yes && BaseImpl.UpdateTableField(ResourceKeys.SettingTableName, "formKey", "varchar(200)")) { MessageUtil.Show(ResourceKeys.UpdateSuccess); } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("保存表格属性出错", ex); MessageUtil.Show(ex); } } } /// /// 说明:列右键菜单扩展 /// 创建人:王一帆 /// 创建日期:2019-09-11 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// /// protected void OnGridViewPopupMenuShowing(object sender, PopupMenuShowingEventArgs e) { if (e.MenuType == GridMenuType.Column) { GridViewColumnMenu columnMenu = e.Menu as GridViewColumnMenu; DXMenuItem itemSaveColumn = new DXMenuItem("保存表格属性", SaveItemClick); DXMenuItem itemResetColumn = new DXMenuItem("重置表格属性", ResetItemClick); itemSaveColumn.BeginGroup = true; itemSaveColumn.Tag = e.HitInfo.Column; columnMenu.Items.AddRange(new DXMenuItem[] { itemSaveColumn, itemResetColumn }); } } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public void SetGridViewColumns(DataTable table) { AddConditions = string.Empty; this._popup.GridViewObj.Columns.Clear(); if (table != null && this._popup.GridViewObj.Columns.Count == 0) { int popWidth = 200; GridColumn valueColumn = new GridColumn(); valueColumn.Name = valueColumn.FieldName = ValueField; valueColumn.Caption = "编码"; valueColumn.Visible = true; valueColumn.Width = 60; //字段第一个字符为下划线代表不显示 if (string.IsNullOrEmpty(ValueField) || ValueField.Substring(0, 1) == "_") valueColumn.Visible = false; GridColumn textColumn = new GridColumn(); textColumn.Name = textColumn.FieldName = TextMember; textColumn.Caption = "名称"; textColumn.Visible = true; textColumn.Width = 120; //字段第一个字符为下划线代表不显示 if (string.IsNullOrEmpty(TextMember) || TextMember.Substring(0, 1) == "_") textColumn.Visible = false; this._popup.GridViewObj.Columns.AddRange(new GridColumn[] { valueColumn, textColumn }); if (table.Columns.IndexOf("remark") != -1) { DataColumn column = table.Columns.Cast().FirstOrDefault(x => x.ColumnName.ToLower() == RemarkField); if (column != null) RemarkField = column.ColumnName; GridColumn remarkColumn = new GridColumn(); remarkColumn.Name = remarkColumn.FieldName = RemarkField; remarkColumn.Caption = "备注"; remarkColumn.Visible = true; remarkColumn.Width = 120; //字段第一个字符为下划线代表不显示 if (RemarkField.Substring(0, 1) == "_") remarkColumn.Visible = false; this._popup.GridViewObj.Columns.Add(remarkColumn); _hasRemark = true; } foreach (DataColumn dcol in table.Columns) { if ((dcol.ColumnName.Substring(0, 1) != "_") && (dcol.ColumnName.ToLower() != ValueField.ToLower()) && (dcol.ColumnName.ToLower() != TextMember.ToLower()) && (dcol.ColumnName.ToLower() != RemarkField.ToLower()) && ((int)dcol.ColumnName[0] > 127)) { GridColumn otherColumn = new GridColumn(); otherColumn.Name = otherColumn.FieldName = otherColumn.Caption = dcol.ColumnName; otherColumn.Visible = true; otherColumn.Width = 80; this._popup.GridViewObj.Columns.Add(otherColumn); AddConditions += "or " + otherColumn.Name + " like '%{3}%'"; } } this.SetCustomColumns(); this._popup.Width = popWidth; } } /// /// 说明:计算控件Size,只计算一次 /// 创建人:龚宇超 /// 创建日期:2018-04-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The object. protected virtual void CalcPopupSize(object obj) { if (this._Handed) return; this._Handed = true; try { AutoGridRevPopup popupObj = obj as AutoGridRevPopup; if (popupObj != null && IsBestFitColumns) { if (this.InvokeRequired) { this.Invoke((EventHandler)delegate { int calcLen = this.Popup.GridViewObj.DataRowCount > 20 ? 20 : this.Popup.GridViewObj.DataRowCount; DataTable table = this.Popup.GridControlObj.DataSourceTable(); bool hasReamrkField = table.Columns.Contains(RemarkField); int iValueWidth = 0, iTextWidth = 0, iRemarkWidth = 0, iOtherWidth = 0; int iIndexWidth = popupObj.GridViewObj.IndicatorWidth; for (int i = 0; i < calcLen; i++) { string valueValue = ValueMember.Substring(0, 1) != "_" ? table.Rows[i][ValueMember] + "" : ""; string textValue = TextMember.Substring(0, 1) != "_" ? table.Rows[i][TextMember] + "" : ""; string remarkValue = hasReamrkField ? table.Rows[i][RemarkField] + "" : ""; int valueWidth = GraphicsText.GetTextWidth(valueValue); int textWidth = GraphicsText.GetTextWidth(textValue); int remarkWidth = GraphicsText.GetTextWidth(remarkValue); if (iValueWidth < valueWidth) iValueWidth = valueWidth; if (iTextWidth < textWidth) iTextWidth = textWidth; if (iRemarkWidth < remarkWidth) iRemarkWidth = remarkWidth; } foreach (GridColumn col in this.Popup.GridViewObj.Columns) { if (col.FieldName.Substring(0, 1) != "_" && col.FieldName.ToLower() != ValueField.ToLower() && col.FieldName.ToLower() != TextMember.ToLower() && col.FieldName.ToLower() != RemarkField.ToLower()) { col.Width = col.GetBestWidth(); iOtherWidth += col.Width; } } // 由于计算有误差,所以计算列结果都加10px iValueWidth = iValueWidth < 50 ? 50 : iValueWidth + 10; iTextWidth = iTextWidth + 10; popupObj.GridViewObj.Columns[ValueMember].Width = iValueWidth; popupObj.GridViewObj.Columns[TextMember].Width = iTextWidth; if (hasReamrkField) { popupObj.GridViewObj.Columns[RemarkField].Width = iRemarkWidth; iRemarkWidth = iRemarkWidth + 10; } int popupWidth = iIndexWidth + iValueWidth + iTextWidth + iRemarkWidth + iOtherWidth + 20; if (popupWidth > popupObj.Width) popupObj.Width = popupWidth > this._maxPopupWidth ? this._maxPopupWidth : popupWidth; //this.CalcPopupLocation(); this._Handed = false; }); } } } catch (Exception) { throw; } } /// /// 说明:值为空时弹出搜索界面 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected void OnAutoGridLookUpGotFocus(object sender, EventArgs e) { System.Threading.Thread thread = new Thread(() => { while (!this.IsSetDataSource) { } this.HandPopupSqlValue(this.Text); ShowPopup(); }); thread.Start(); } /// /// 鼠标单击控件时 /// /// /// protected void OnAutoGridRevLookUpMouseClick(object sender, EventArgs e) { if (this._popup.Visible == false) { System.Threading.Thread thread = new Thread(() => { while (!this.IsSetDataSource) { } this.HandPopupSqlValue(this.Text); ShowPopup(); }); thread.Start(); } } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2018-03-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected void OnPopupGridViewEnter(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { this.GotFocus -= new EventHandler(OnAutoGridLookUpGotFocus); this.HidePopup(); this.SetValue(); if (this.OnSearchCallBack != null) { OnSearchCallBack(this, null); } this.GotFocus += new EventHandler(OnAutoGridLookUpGotFocus); } } /// /// 说明:鼠标回调 /// 创建人:龚宇超 /// 创建日期:2018-03-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected void OnPopupGridViewMouseClick(object sender, EventArgs e) { this.GotFocus -= new EventHandler(OnAutoGridLookUpGotFocus); this.HidePopup(); this.SetValue(); if (this.OnSearchCallBack != null) { OnSearchCallBack(this, null); } this.GotFocus += new EventHandler(OnAutoGridLookUpGotFocus); } /// /// 说明:搜索框离开焦点时 /// 创建人:王一帆 /// 创建日期:2020-09-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected void OnAutoGridLookUpleave(object sender, EventArgs e) { if (this.Model != null && !string.IsNullOrEmpty(this.Text) && string.IsNullOrEmpty(getValueItem(this.Text)) && (ControlType.LabAutoCompleteValue == Model.FieldType || ControlType.LabAutoCompleteValueParam == Model.FieldType) && !this.IsKeyDownFocusd) { this.Text = string.Empty; } } /// /// 说明:失去焦点关闭界面 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected void OnAutoGridLookUpLostFocus(object sender, EventArgs e) { if (!this._popup.Focused && !this._popup.GridControlObj.Focused && !this.Focused && !this.IsKeyDownFocusd) { this.HidePopup(); } if (this.Model != null && !string.IsNullOrEmpty(this.Text) && string.IsNullOrEmpty(getValueItem(this.Text)) && (ControlType.LabAutoCompleteValue == Model.FieldType || ControlType.LabAutoCompleteValueParam == Model.FieldType) && !this.IsKeyDownFocusd) { this._value = string.Empty; this.Text = string.Empty; } } /// /// 说明:鼠标弹起时刷新数据 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected void OnAutoGridLookUpKeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down) { this.IsKeyDownFocusd = true; this._popup.Focus(); this.IsKeyDownFocusd = false; } //this.ShowPopup(); } /// /// 说明:判断输入的是否是中文 /// 创建人:龚宇超 /// 创建日期:2018-03-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public bool IsChina(string CString) { Console.WriteLine("{0}", CString.Length); bool BoolValue = false; for (int i = 0; i < CString.Length; i++) { if (Convert.ToInt32(Convert.ToChar(CString.Substring(i, 1))) > 128) { BoolValue = true; return BoolValue; } } return BoolValue; } /// /// 判断输入的字符串是否存在数字 /// /// /// public static bool IsNumberic(string str) { try { bool BoolValue = false; for (int i = 0; i < str.Length; i++) { if (Char.IsNumber(str, i)) { BoolValue = true; break; } } return BoolValue; } catch (Exception ex) { return false; } } /// /// 值改变时刷新 /// /// /// private void AutoGridLookUp_TextChanged(object sender, EventArgs e) { if (PopShowFlag) { if (SystemInfo.Instance.TrimWhiteSpace) this.HandPopupSqlValueNew(this.Text.Trim());//使用原来的方法 else this.HandPopupSqlValueNew(this.Text); this.ShowPopup(); } this.PopShowFlag = true; } private void HandPopupSqlValueNew(object searchText) { if (!string.IsNullOrEmpty(SourceSQL)) { // 数据库搜索 string sqlValue = string.Empty; if (SourceSQL.ToLower().StartsWith("exec")) { // 存储过程处理 sqlValue = SourceSQL; if (sqlValue.Contains("{" + ValueField + "}")) sqlValue = sqlValue.Replace("{" + ValueField + "}", searchText + ""); if (sqlValue.Contains("{" + TextMember + "}")) sqlValue = sqlValue.Replace("{" + TextMember + "}", searchText + ""); if (sqlValue.Contains("{" + RemarkField + "}")) sqlValue = sqlValue.Replace("{" + RemarkField + "}", searchText + ""); if (this.ControlObj != null) sqlValue = this.ControlObj.ReplaceControlValue(sqlValue); sqlValue = ProcessingSql(sqlValue); sqlValue = MainImpl.GetDefaultValue(SourceSQL); sqlValue = ReplaceHelper.ReplaceParam(SourceSQL); } else { // SQL处理 string remarkCond = string.Empty; bool nonEnglish = false;//是否全是英文 if (IsChina(searchText + "") || IsNumberic(searchText + "")) { nonEnglish = true; } if (this._hasRemark) { if (nonEnglish) { remarkCond = string.Format(" or {0} like '%{1}%' ", RemarkField, (searchText + "").Replace("[", "[[]")); } else { remarkCond = string.Format(" or {0} like '%{1}%' or dbo.P_getpy({0}) like '%{1}%'", RemarkField, (searchText + "").Replace("[", "[[]")); } } //SourceSQL = ProcessingSql(SourceSQL); //SourceSQL = MainImpl.GetDefaultValue(SourceSQL); //SourceSQL = ReplaceHelper.ReplaceParam(SourceSQL);//同类似方法 if (nonEnglish) { string sql = "select top 500 * from ({0}) temp where {1} like '%{3}%' or {2} like '%{3}%' "; sqlValue = string.Format(sql + remarkCond + AddConditions, SourceSQL, ValueField, TextMember, (searchText + "").Replace("[", "[[]")); } else { string sql = "select top 500 * from ({0}) temp where {1} like '%{3}%' or {2} like '%{3}%' or dbo.P_getpy({2}) like '%{3}%' "; sqlValue = string.Format(sql + remarkCond + AddConditions, SourceSQL, ValueField, TextMember, (searchText + "").Replace("[", "[[]")); } if (Model != null && !string.IsNullOrEmpty(Model.AddOrderByCond)) { sqlValue = string.Format("{0} {1}", sqlValue, Model.AddOrderByCond); } sqlValue = MainImpl.GetDefaultValue(sqlValue); } //带参数sql,处理 if (this.ControlObj != null && Regex.IsMatch(SourceSQL, ReplaceHelper.ReplaceParamKey)) { string sourceSql = sqlValue; // Step 1:替换SpeciesNo List condition = ReplaceHelper.GetParamFields(sourceSql); if (!string.IsNullOrEmpty(SpeciesValue)) { foreach (string item in condition) { string field = item.Replace("{", "").Replace("}", ""); if ("speciesno".Equals(field, StringComparison.OrdinalIgnoreCase)) { sourceSql = sourceSql.Replace(item, SpeciesValue); } } } // Step 2:替换SpeciesNo if (this.ControlObj.CurrentData != null && this.ControlObj.CurrentData.Table.Columns.Contains("SpeciesNo")) { foreach (string item in condition) { string field = item.Replace("{", "").Replace("}", ""); if ("speciesno".Equals(field, StringComparison.OrdinalIgnoreCase)) { sourceSql = sourceSql.Replace(item, this.ControlObj.CurrentData["SpeciesNo"] + ""); } } } sqlValue = ControlObj.ReplaceControlValue(sourceSql.Replace("#", "")); } if (!this._working) { Thread thread = new Thread(new ParameterizedThreadStart(RefreshPopupDataSourceNew)); thread.IsBackground = true; thread.Start(sqlValue); } else { this._queryQueue.Add(sqlValue); } } } private void RefreshPopupDataSourceNew(object sqlValue) { try { if (this.InvokeRequired) { this.Invoke(new EventHandler(delegate { this._working = true; this.Popup.LabelObj.Text = "正在筛选数据,请稍后..."; this.Popup.BottomPanelObj.Visible = true; this.Popup.GridControlObj.DataSourceTable().Clear(); })); } DateTime beginTime = DateTime.Now; //DataTable table = MainImpl.GetDataTableResult(sqlValue + ""); DataTable table = new DataTable(); if (!string.IsNullOrWhiteSpace(sqlValue + "")) { try { table = SqlHelper.ExecuteDataTable(sqlValue + ""); } catch (Exception) { table = new DataTable(); } } DateTime endTime = DateTime.Now; if (this._queryQueue.Count > 0) { // 在检索过程中还存在输入数据,则拿最后一次数据在进行匹配一次 Thread thread = new Thread(new ParameterizedThreadStart(RefreshPopupDataSourceNew)); thread.IsBackground = true; thread.Start(this._queryQueue.Last()); this._queryQueue.Clear(); } else { if (this.InvokeRequired) { this.Invoke(new EventHandler(delegate { int second = Convert.ToInt32((endTime - beginTime).TotalSeconds); string tipMsg = "数据筛选完成."; this.Popup.LabelObj.Text =