using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using DevExpress.XtraGrid.Views.Grid; using Lskj.Control.Model; using System.Reflection; using DevExpress.Data.Filtering; using DevExpress.XtraGrid.Columns; using Lskj.Util; using Lskj.Business; using Lskj.Business.Impl; using DevExpress.Utils; using DevExpress.XtraEditors.Controls; using System.Text.RegularExpressions; namespace Lskj.Control { public partial class LabelAutoGridLook : BaseUserControl { /// /// 隐藏值改变时触发 /// public event EventHandler HiddenValueChange; /// /// 刷新数据源 /// public event EventHandler RefreshDataSource; protected GridView CurrentOperGridView = null; protected string CurrentOperColumnKey = string.Empty; /// /// 是否处理过计算 /// private bool _Handed; /// /// 弹出框最大宽度 /// private int _maxPopupWidth = 800; private string _value; private string _textVlaue; private bool _hasRemark = false; /// /// 后台线程是否在执行中 /// private bool _working = false; private List _queryQueue = new List(); /// /// 是否点击弹出框中的行 /// private bool PopupBoxSelection = false; /// /// 显示值字段 /// public string TextField { get { return this.TextMember; } set { this.TextMember = value; } } /// /// 新增模糊查询条件 /// 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 GridLookUpEdit TextEdit { get { return edit; } } /// /// 是否带参数 /// public bool Isparameters = false; /// /// 文本 /// /// The label. public Label Label { get { return lblText; } } /// /// 按钮 /// /// The label. public SimpleButton Button { get { return btnRefresh; } } /// /// 说明:设置控件值 /// 创建人:龚宇超 /// 创建日期:2017-08-07 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public override string EditText { get { return this.TextEdit.Text; } set { this.EditValue = value; } } /// /// 获取隐藏值 /// /// The edit value. //public string EditValue //{ // get // { // return this.Edit_Value + ""; // } //} /// /// 只读文本颜色 /// /// The color of the read only label. public override bool ReadOnly { get { return base.ReadOnly; } set { base.ReadOnly = value; this.TextEdit.Properties.ReadOnly = value; this.lblText.ForeColor = value ? base.ReadOnlyLabelForceColor : Required ? base.RequiredLabelForceColor : base.DefaultLabelForceColor; } } /// /// 控件Model /// /// The model. public override ControlModel Model { get { return base.Model; } } /// /// 必填文本颜色 /// /// The color of the required label. public override bool Required { get { return base.Required; } set { base.Required = value; if (value) { this.Label.ForeColor = base.RequiredLabelForceColor; } } } /// /// 隐藏值 /// /// The value. public new string EditValue { get { BaseUserControl control = null; if (this.Model != null) control = ControlObj.FindControl(this.Model.FieldName); if (this.Model != null && (this.Model.FieldType == ControlType.LabAutoGridText || this.Model.FieldType == ControlType.LabAutoGridTextParam)) { // 自动搜索框显示名称、自动搜索框显示名称带参数时,直接显示与保存值,此时值可以任意输入,无需匹配数据源. if (this.DataSource != null && this.DataSource is DataTable) { DataTable table = this.DataSourceTable != null ? this.DataSourceTable : this.DataSource as DataTable; DataRow rowItem = table.Select("1=1").FirstOrDefault(x => control.EditText == x[TextMember] + ""); if (rowItem == null) { rowItem = (this.DataSource as DataTable).Select("1=1").FirstOrDefault(x => control.EditText == x[TextMember] + ""); if (rowItem == null) return ""; } } } if (this.Model != null && (this.Model.FieldType == ControlType.LabAutoGridValue || this.Model.FieldType == ControlType.LabAutoGridValueParam)) { // 存在名称并且没有value值则 //PopupBoxSelection为ture时代表在弹出框中选中行,就不根据当前输入值判断了(可能输入一半查询到后就直接选中,或者输入123,选中1234,但是control.EditText值还是123导致出错) if (control != null && !string.IsNullOrEmpty(control.EditText) && (string.IsNullOrEmpty(_value) || !control.EditText.Equals(this._textVlaue)) && !PopupBoxSelection) { if (this.DataSource != null && this.DataSource is DataTable) { DataTable table = this.DataSourceTable != null ? this.DataSourceTable : this.DataSource as DataTable; DataRow rowItem = table.Select("1=1").FirstOrDefault(x => control.EditText == x[TextMember] + ""); if (rowItem != null) { return rowItem[ValueMember] + ""; } else { rowItem = (this.DataSource as DataTable).Select("1=1").FirstOrDefault(x => control.EditText == x[ValueMember] + ""); if (rowItem != null) { return rowItem[ValueMember] + ""; } } } } } return control != null && string.IsNullOrEmpty(control.EditText) ? "" : _value; } set { 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._textVlaue = rowItem[TextMember] + ""; this.TextEdit.EditValue = rowItem[ValueMember] + ""; this.edit.SelectionStart = this.Text.Length; } else { rowItem = (this.DataSource as DataTable).Select("1=1").FirstOrDefault(x => value == x[ValueMember] + ""); if (rowItem != null) { this._value = rowItem[ValueMember] + ""; this._textVlaue = rowItem[TextMember] + ""; this.TextEdit.EditValue = rowItem[ValueMember] + ""; this.edit.SelectionStart = this.Text.Length; } else { this._value = string.Empty; this._textVlaue = string.Empty; this.TextEdit.EditValue = string.Empty; } } } else { this._value = string.Empty; this._textVlaue = string.Empty; this.TextEdit.EditValue = string.Empty; } //if (HiddenValueChange != null) HiddenValueChange(this.TextEdit, null); } } /// /// 说明:设置控件显示文本 /// 创建人:龚宇超 /// 创建日期:2017-08-07 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// 显示Lebel文本 public override string LabelText { get { return this.lblText.Text; } set { this.lblText.Text = value; if (FontSize > 0) { this.plLeft.Dock = DockStyle.Left; this.plLeft.AutoSize = false; this.lblText.AutoSize = false; this.lblText.Dock = System.Windows.Forms.DockStyle.Fill; this.lblText.Location = new System.Drawing.Point(0, 0); this.lblText.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.edit.Properties.AutoHeight = false; this.plLeft.Width = value.Length * GetCharWidth(); GetCharWidthMultilingual(this.lblText, this.lblText.Text, this.plLeft); } else { this.plLeft.Width = this.lblText.Width + PaddingLeft; } } } /// /// 字体大小 /// /// The size of the control. public override float FontSize { get { return base.FontSize; } set { base.FontSize = value; if (value > 0) { this.lblText.Font = new Font(this.lblText.Font.FontFamily, value); this.edit.Font = new Font(this.edit.Font.FontFamily, value); } } } /// /// 说明:设置数据源 /// 创建人:龚宇超 /// 创建日期:2018-02-26 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The data source. public void SetDataSource(DataTable dataSource) { this.edit.Properties.View.OptionsView.ShowIndicator = false; this.edit.Properties.View.OptionsView.ColumnAutoWidth = false; this.edit.Properties.AutoComplete = false; this.edit.Properties.PopupSizeable = true; this.edit.Properties.PopupResizeMode = ResizeMode.Default; this.edit.Properties.AllowFocused = true; this.edit.Properties.ImmediatePopup = true; this.edit.Properties.ShowFooter = false; this.edit.Properties.NullText = ""; this.edit.Properties.TextEditStyle = TextEditStyles.Standard; this.edit.Properties.PopupBorderStyle = PopupBorderStyles.Flat; this.edit.Properties.AllowNullInput = DefaultBoolean.False; this.edit.Properties.ShowPopupShadow = true; this.edit.Properties.ValueMember = ValueMember; this.edit.Properties.DisplayMember = TextMember; this.edit.Properties.View.Appearance.HeaderPanel.TextOptions.HAlignment = HorzAlignment.Center; DataRow dr = dataSource.NewRow(); dataSource.Rows.Add(dr); this.edit.Properties.DataSource = dataSource; this.SetGridViewColumns(dataSource); this.DataSourceTable = dataSource.Copy(); } /// /// 设置数据源 /// /// The data source. public object DataSource { get { return this != null ? this.edit.Properties.DataSource : null; } set { if (value != null) { this.edit.Properties.DataSource = value; } } } /// /// 数据源(用于匹配数据) /// public DataTable DataSourceTable; public string SpeciesValue; public LabelAutoGridLook() { InitializeComponent(); InitializeEvent(); } /// /// 说明:初始化事件 /// 创建人:王一帆 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void InitializeEvent() { try { this.Disposed += new EventHandler(OnLabelAutoGridLook_Disposed); this.edit.QueryPopUp += new CancelEventHandler(OnSearchEditQueryPopUp); GridView gridView = edit.Properties.View as GridView; gridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.OnGridClickChanged); gridView.KeyPress += GridView_KeyPress; this.btnRefresh.Click += BtnRefresh_Click; } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 刷新按钮点击,刷新数据源 /// /// /// private void BtnRefresh_Click(object sender, EventArgs e) { if (RefreshDataSource != null) RefreshDataSource(this, e); } /// /// 说明:带参数自动搜索框 /// 创建人:龚宇超 /// 创建日期:2018-04-28 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected void OnSearchEditQueryPopUp(object sender, CancelEventArgs e) { try { this.HandPopupSqlValue(this.Text); } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2018-03-21 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public void HandPopupSqlValue(object searchText) { if (string.IsNullOrEmpty(SourceSQL)) { // 本地搜索 } else { // 数据库搜索 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); } //else //{ // // SQL处理 // string remarkCond = string.Empty; // if (this._hasRemark) // remarkCond = string.Format(" or {0} like '%{1}%' or dbo.P_getpy({0}) like '%{1}%'", RemarkField, searchText); // sqlValue = string.Format("select top 500 * from ({0}) temp where {1} like '%{3}%' or {2} like '%{3}%' or dbo.P_getpy({2}) like '%{3}%' " + remarkCond + AddConditions, SourceSQL, ValueField, TextMember, searchText); //} // 带参数sql,处理 if ((this.ControlObj != null && Regex.IsMatch(SourceSQL, ReplaceHelper.ReplaceParamKey)) || Isparameters) { string sourceSql = SourceSQL; // 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("#", "")); DataTable table = MainImpl.GetDataTableResult(sqlValue + ""); this.edit.Properties.DataSource = table; } } } /// /// 说明:获取顶层窗口 /// 创建人:龚宇超 /// 创建日期: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 SetGridViewColumns(DataTable table) { int popWidth = 0; GridColumn valueColumn = new GridColumn(); valueColumn.Name = valueColumn.FieldName = ValueField; valueColumn.Caption = "编码"; valueColumn.Visible = ValueMember.Substring(0, 1) != "_"; GridColumn textColumn = new GridColumn(); textColumn.Name = textColumn.FieldName = TextField; textColumn.Caption = "名称"; textColumn.Visible = TextField.Substring(0, 1) != "_"; this.edit.Properties.View.Columns.AddRange(new GridColumn[] { valueColumn, textColumn }); if (table.Columns.Contains("remark")) { GridColumn remarkColumn = new GridColumn(); remarkColumn.Caption = "备注"; remarkColumn.Name = remarkColumn.FieldName = "remark"; remarkColumn.Visible = true; this.edit.Properties.View.Columns.Add(remarkColumn); } string[] columnsWidth = Model != null ? Model.LookUpFieldsWidth.Trim().TrimEnd(',').Split(',') : null; if (Model != null && !string.IsNullOrWhiteSpace(Model.LookUpFieldsWidth) && columnsWidth.Length > 0) { int columnWidthIndex = 0; foreach (DataColumn dcol in table.Columns) { if ((dcol.ColumnName.Substring(0, 1) != "_")) { if ((dcol.ColumnName.ToLower() != ValueMember.ToLower()) && (dcol.ColumnName.ToLower() != TextMember.ToLower()) && (dcol.ColumnName.ToLower() != "remark") && ((int)dcol.ColumnName[0] > 127)) { GridColumn otherColumn = new GridColumn(); otherColumn.Name = otherColumn.FieldName = otherColumn.Caption = dcol.ColumnName; otherColumn.Visible = true; this.edit.Properties.View.Columns.Add(otherColumn); } if (this.edit.Properties.View.Columns.FirstOrDefault(x => x.FieldName == dcol.ColumnName) != null) { GridColumn gCol = this.edit.Properties.View.Columns[dcol.ColumnName]; int width = 0; if (columnWidthIndex < columnsWidth.Length) { string widthStr = columnsWidth[columnWidthIndex]; width = int.TryParse(widthStr, out width) ? width : CalcMaxColumnWidth(table, gCol.Name); columnWidthIndex += 1; } else { width = CalcMaxColumnWidth(table, gCol.Name); } gCol.Width = width; popWidth += gCol.Width; } } } } else { foreach (DataColumn dcol in table.Columns) { if ((dcol.ColumnName.Substring(0, 1) != "_")) { if ((dcol.ColumnName.ToLower() != ValueMember.ToLower()) && (dcol.ColumnName.ToLower() != TextMember.ToLower()) && (dcol.ColumnName.ToLower() != "remark") && ((int)dcol.ColumnName[0] > 127)) { GridColumn otherColumn = new GridColumn(); otherColumn.Name = otherColumn.FieldName = otherColumn.Caption = dcol.ColumnName; otherColumn.Visible = true; this.edit.Properties.View.Columns.Add(otherColumn); } if (this.edit.Properties.View.Columns.FirstOrDefault(x => x.FieldName == dcol.ColumnName) != null) { GridColumn gCol = this.edit.Properties.View.Columns[dcol.ColumnName]; gCol.Width = CalcMaxColumnWidth(table, gCol.Name); popWidth += gCol.Width; } } } } if (Model != null && Model.LookUpWidth > 0) { popWidth = Model.LookUpWidth; } this.edit.Properties.PopupFormSize = new System.Drawing.Size(popWidth, this.edit.Properties.PopupFormSize.Height); this.edit.Properties.EditValueChanging += gridLookUpEdit1_EditValueChanging; } /// /// 搜索框输入筛选事件 /// /// /// private void gridLookUpEdit1_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e) { GridLookUpEdit edit = sender as GridLookUpEdit; if (string.IsNullOrWhiteSpace(edit.AutoSearchText)) return; BeginInvoke(new MethodInvoker(delegate () { FilterLookup(sender); })); } /// /// 筛选完成 /// /// private void FilterLookup(object sender) { try { GridLookUpEdit edit = sender as GridLookUpEdit; GridView gridView = edit.Properties.View as GridView; GridColumnModel model = edit.Properties.Tag as GridColumnModel; DataTable table = edit.Properties.DataSource as DataTable; string str = edit.AutoSearchText; if (!string.IsNullOrWhiteSpace(str)) { // str = Regex.Replace(str, "[^0-9A-Za-z]", ""); } FieldInfo fi = gridView.GetType().GetField("extraFilter", BindingFlags.NonPublic | BindingFlags.Instance); List strList = new List(); foreach (GridColumn colum in gridView.Columns) { BinaryOperator op1 = new BinaryOperator(colum.FieldName, "%" + str + "%", BinaryOperatorType.Like); strList.Add(op1); } string filterCondition = new GroupOperator(GroupOperatorType.Or, strList.ToArray()).ToString(); fi.SetValue(gridView, filterCondition); MethodInfo mi = gridView.GetType().GetMethod("ApplyColumnsFilterEx", BindingFlags.NonPublic | BindingFlags.Instance); mi.Invoke(gridView, null); } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2019-06-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The d table. /// Name of the column. /// System.Int32. public int CalcMaxColumnWidth(DataTable dTable, string columnName) { int maxWidth = 0, maxRow = 20; for (int i = 0; i < dTable.Rows.Count; i++) { if (i < maxRow) { DataRow row = dTable.Rows[i]; int columnWidth = GraphicsText.GetTextWidth(row[columnName] + ""); if (columnWidth > maxWidth) { maxWidth = columnWidth; } } } return maxWidth; } /// /// 实际值发生改变触发 /// /// /// private void OnGridClickChanged(object sender, EventArgs e) { try { this.PopupBoxSelection = true; GridView gridView = sender as GridView; DataRow rowItem = gridView.GetFocusedDataRow(); if (rowItem != null && rowItem.Table.Columns.Contains(ValueMember)) { this.EditValue = rowItem[ValueMember] + ""; } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } finally { this.PopupBoxSelection = false; } } private void GridView_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) { try { GridView gridView = sender as GridView; DataRow rowItem = gridView.GetFocusedDataRow(); if (rowItem != null && rowItem.Table.Columns.Contains(ValueMember)) { this.EditValue = rowItem[ValueMember] + ""; } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } } /// /// 说明:释放时清理数据源 /// 创建人:龚宇超 /// 创建日期:2018-03-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 private void OnLabelAutoGridLook_Disposed(object sender, EventArgs e) { if (this.DataSourceTable != null) { this.DataSourceTable.Clear(); this.DataSourceTable.Dispose(); } if (this.DataSource != null) { this.DataSource = null; } GC.Collect(); } /// /// 背景颜色 /// /// The color of the required label. public override Color BackgroundColor { get { return TextEdit.Properties.Appearance.BackColor; } set { TextEdit.Properties.Appearance.BackColor = value; } } /// /// 前景颜色 /// /// The color of the required label. public override Color ForeColor { get { return TextEdit.Properties.Appearance.ForeColor; } set { TextEdit.Properties.Appearance.ForeColor = value; } } /// /// 内容加粗 /// /// The color of the required label. public override bool ContentBold { get { return TextEdit.Properties.Appearance.Font.Bold; } set { Font oldFont = TextEdit.Properties.Appearance.Font; TextEdit.Properties.Appearance.Font = new Font(oldFont.FontFamily, oldFont.Size, value ? FontStyle.Bold : FontStyle.Regular); } } } }