1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.ComponentModel;
- using System.Data;
- namespace LYFZ.ComponentLibrary
- {
- public class DataGridViewEx : System.Windows.Forms.DataGridView
- {
- /// <summary>
- /// 实现分页后
- /// </summary>
- public DataGridViewEx(): base()
- {
- try
- { RefreshTheme(); }
- catch { }
- this.SetStyle(ControlStyles.DoubleBuffer, true);
- this.SetStyle(ControlStyles.UserPaint, true);
- this.SetStyle(ControlStyles.ResizeRedraw, true);
- this.UpdateStyles();
- this.ColumnDisplayIndexChanged += DataGridViewEx_ColumnDisplayIndexChanged;
- this.ColumnWidthChanged += DataGridViewEx_ColumnWidthChanged;
- this.Paint += DataGridViewEx_Paint;
- this.CellMouseDown += DataGridViewEx_CellMouseDown;
- this.RowsAdded += DataGridViewEx_RowsAdded;
- this.CellPainting += DataGridViewEx_CellPainting;
- this.KeyDown += DataGridViewEx_KeyDown;
- }
- /// <summary>
- /// 设置要隐藏的手机号字段名
- /// </summary>
- void SetHidePhoneCellsName()
- {
- if (this.Columns != null)
- {
- HidePhoneFindList.Clear();
- for (int i = 0; i < this.Columns.Count; i++)
- {
- DataGridViewColumn Column = this.Columns[i];
- if (_HidePhoneCellsNameList.Contains(Column.Name) || _HidePhoneCellsNameList.Contains(Column.HeaderText))
- {
- HidePhoneFindList.Add(Column.Name);
- }
- }
- }
- }
- // string[] HidePhoneFinds = "客户电话,电话,固定电话,介绍人电话,手机号码,本人手机,老公手机".Split(',');
- List<string> HidePhoneFindList = new List<string>();
- /// <summary>
- ///
- /// </summary>
- static List<string> _HidePhoneCellsNameList = new List<string>();//当前手机号字段列名
- /// <summary>
- /// 要将字段值显示为“*”号的字段列名(当前手机号字段列名)
- /// </summary>
- public static List<string> HidePhoneCellsNameList
- {
- get { return DataGridViewEx._HidePhoneCellsNameList; }
- }
- void DataGridViewEx_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
- {
- if (_HidePhoneCellsNameList.Count > 0)
- {
- if (e.RowIndex == 0)
- {
- SetHidePhoneCellsName();
- }
- if (LYFZ.BLL.BLL_ErpUser.GetRights(LYFZ.BLL.BLL_ErpUser.CurrentUserRights.OtherPermissionsSet, LYFZ.CustomAttributes.OperatingAuthority.ProhibitViewCustomerPhoneNumber) && !LYFZ.BLL.BLL_ErpUser.IsAdministrator() && HidePhoneCellsNameList.Count > 0)
- {
- try
- {
- foreach (string HidePhoneCellsName in HidePhoneFindList)
- {
- this.Rows[e.RowIndex].Cells[HidePhoneCellsName].Tag = this.Rows[e.RowIndex].Cells[HidePhoneCellsName].Value;
- this.Rows[e.RowIndex].Cells[HidePhoneCellsName].Value = LYFZ.Command.Command_Validate.HidePhone(this.Rows[e.RowIndex].Cells[HidePhoneCellsName].Value);
- }
- }
- catch { }
- }
- }
- }
- bool _EraseCell = false;
- /// <summary>
- /// 是否开启擦除单元格功能
- /// </summary>
- public bool EraseCell
- {
- get { return _EraseCell; }
- set { _EraseCell = value; }
- }
- public string EraseCellDrawLine
- {
- get { return "@EraseCellDrawLine@"; }
- }
- public string EraseCellDrawLineVEnd
- {
- get { return "@EraseCellDrawLine@VEnd"; }
- }
- public string EraseCellDrawLineHEnd
- {
- get { return "@EraseCellDrawLine@HEnd"; }
- }
- public string EraseCellDrawLineVHEnd
- {
- get { return "@EraseCellDrawLine@VHEnd"; }
- }
- /// <summary>
- /// 擦除单元格
- /// </summary>
- /// <param name="e"></param>
- void EraseCellPainting(DataGridViewCellPaintingEventArgs e)
- {
- if (EraseCell)
- {
- if (e.RowIndex < 0 || e.ColumnIndex < 0) { return; }
- Brush gridBrush = new SolidBrush(this.GridColor);
- SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
- object EraseCellValue = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag;
- if (EraseCellValue != null && (EraseCellValue.ToString().ToLower().Contains(EraseCellDrawLine.ToLower())))
- {
- // cellwidth = e.CellBounds.Width;
- Pen gridLinePen = new Pen(gridBrush);
- if (this.Rows[e.RowIndex].Selected)
- {
- backBrush.Color = e.CellStyle.SelectionBackColor;
- }
- //以背景色填充
- e.Graphics.FillRectangle(backBrush, e.CellBounds);
- if (EraseCellValue.ToString().ToLower() == EraseCellDrawLineHEnd.ToLower() || EraseCellValue.ToString().ToLower() == EraseCellDrawLineVHEnd.ToLower())
- {
- //画下面的线
- e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
- }
- if (EraseCellValue.ToString().ToLower() == EraseCellDrawLineVEnd.ToLower() || EraseCellValue.ToString().ToLower() == EraseCellDrawLineVHEnd.ToLower())
- {
- // 画右边线
- e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
- }
- e.Handled = true;
- }
- }
- }
- /// <summary>
- /// 纵向合并,即合并数据项的值
- /// </summary>
- /// <param name="e"></param>
- private void DataGridViewEx_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
- {
- EraseCellPainting(e);
- }
- void DataGridViewEx_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyData == (Keys.Control | Keys.C))
- {
- e.Handled = true;
- }
- }
- /// <summary>
- /// 绘制合并以后的值(纵向) 暂不使用
- /// </summary>
- /// <param name="e"></param>
- /// <param name="cellwidth"></param>
- /// <param name="UpRows"></param>
- /// <param name="DownRows"></param>
- /// <param name="count"></param>
- private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
- {
- string stValue = "";
- if (e.Value != DBNull.Value)
- {
- stValue = e.Value.ToString();
- }
- int fontheight = 0;
- int fontwidth = 0;
- using (SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor))
- {
- fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
- fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
- int cellheight = e.CellBounds.Height;
- if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- }
- }
- bool _isCopyCellValue = true;
- /// <summary>
- /// 是否能复制单元格的Value值
- /// </summary>
- [
- Category("CollapseDataGridViewProperties"),
- Description("是否能复制单元格的Value值"),
- Bindable(true)
- ]
- public bool IsCopyCellValue
- {
- get { return _isCopyCellValue; }
- set { _isCopyCellValue = value; }
- }
- public ContextMenuStripEx conMenu = new ContextMenuStripEx();
- void DataGridViewEx_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
- {
- if (this.Rows.Count > 0)
- {
- if (this.CurrentRow != null)
- {
- if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
- {
- if (e.Button == System.Windows.Forms.MouseButtons.Right)
- {
- this.conMenu.Items.Clear();
- if (IsCopyCellValue)
- {
- // conMenu.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
- conMenu.ItemClicked -= conMenu_ItemClicked;
- conMenu.ItemClicked += conMenu_ItemClicked;
- ToolStripMenuItem item = new ToolStripMenuItem();
- item.Text = "复制" + this.Columns[e.ColumnIndex].HeaderText;
- item.Tag = this.CurrentRow.Index + "|" + e.ColumnIndex;
- item.Name = "复制列";
- conMenu.Items.Add(item);
- }
- if (LYFZ.ComponentLibrary.DataGridViewEx.HidePhoneCellsNameList.Contains(this.Columns[e.ColumnIndex].HeaderText.Trim()))
- {
- if (LYFZ.BLL.OtherCommonModel.GetUserCanViewPhoneCount(LYFZ.BLL.BLL_ErpUser.UsersModel.User_EmployeeID) > 0)
- {
- //conMenu.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
- conMenu.ItemClicked -= conMenu_ItemClicked;
- conMenu.ItemClicked += conMenu_ItemClicked;
- ToolStripMenuItem item = new ToolStripMenuItem();
- item.Text = "查看完整" + this.Columns[e.ColumnIndex].HeaderText;
- item.Tag = this.CurrentRow.Index + "|" + e.ColumnIndex;
- item.Name = "查看列";
- conMenu.Items.Add(item);
- }
- }
- if (conMenu.Items.Count > 0)
- {
- conMenu.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
- }
- }
- }
- else if (e.RowIndex == -1)
- {
- if (this.SelectedRows.Count > 3)
- {
- if (e.Button == System.Windows.Forms.MouseButtons.Right)
- {
- try
- {
- decimal decAoumnt = 0;
- for (int i = 0; i < this.Rows.Count; i++)
- {
- decAoumnt += Convert.ToDecimal(this.Rows[i].Cells[e.ColumnIndex].Value);
- }
- MessageBoxCustom.Show(decAoumnt.ToString().Trim());
- }
- catch { }
- }
- }
- }
- }
- }
- }
- public delegate void DataGridView_ConMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e);
- /// <summary>
- /// 用event 关键字声明事件对象
- /// </summary>
- [Category("控件扩展事件"), Description("列表右击显示菜单事件")]
- public event DataGridView_ConMenu_ItemClicked DataGridViewConMenu_ItemClicked;
- void conMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
- {
- ToolStripItem item = e.ClickedItem;
- if (!string.IsNullOrEmpty(item.Name) && item.Name.Trim() == "复制列")
- {
- if (!string.IsNullOrEmpty(item.Text.Trim()) && item.Tag != null)
- {
- string[] StrTag = item.Tag.ToString().Trim().Split('|');
- Clipboard.SetDataObject(this.Rows[Convert.ToInt32(StrTag[0])].Cells[Convert.ToInt32(StrTag[1])].Value.ToString().Trim());
- }
- }
- else if (!string.IsNullOrEmpty(item.Name) && item.Name.Trim() == "查看列")
- {
- if (!string.IsNullOrEmpty(item.Text.Trim()) && item.Tag != null)
- {
- string[] StrTag = item.Tag.ToString().Trim().Split('|');
- if (LYFZ.BLL.OtherCommonModel.UserCanViewPhoneCount == -2)
- {
- DataTable dt = new LYFZ.BLL.BLL_ErpOrder().GetView_Custom("tb_ErpUser", StrWhere: "User_EmployeeID='" + LYFZ.BLL.BLL_ErpUser.UsersModel.User_EmployeeID + "'", ShowColumnName: "User_LookPhoneQuantity").Tables[0];
- if (dt.Rows.Count > 0)
- { LYFZ.BLL.OtherCommonModel.UserCanViewPhoneCount = Convert.ToInt32(dt.Rows[0]["User_LookPhoneQuantity"]); }
- else
- { LYFZ.BLL.OtherCommonModel.UserCanViewPhoneCount = 0; }
- }
- LYFZ.ComponentLibrary.frmFullPhoneNumber frm = new frmFullPhoneNumber();
- frm.StrUserNumber = LYFZ.BLL.BLL_ErpUser.UsersModel.User_EmployeeID;
- frm.StrPhone = this.Rows[Convert.ToInt32(StrTag[0])].Cells[Convert.ToInt32(StrTag[1])].Tag.ToString().Trim();
- frm.ShowDialog();
- }
- }
- else
- {
- if (this.DataGridViewConMenu_ItemClicked != null)
- { this.DataGridViewConMenu_ItemClicked(sender, e); }
- }
- }
- /// <summary>
- /// 刷新主题
- /// </summary>
- public void RefreshTheme()
- {
- try
- {
- // BackgroundColor = Color.White; //背景颜色
- // BorderStyle = BorderStyle.Fixed3D; //边框样式
- // ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None; //列标题边框样式
- // GridColor = Color.Silver; //单元格网状颜色
- // AllowUserToAddRows = false; //是否显示增加列
- // AllowUserToDeleteRows = false; //是否允许删除
- // AllowUserToOrderColumns = true; //是否手动放置
- SelectionMode = DataGridViewSelectionMode.FullRowSelect;
- AllowUserToResizeRows = false;//不可设置行高
- // RowsDefaultCellStyle.SelectionBackColor = Color.SkyBlue;
- // //改变标题的高度;
- // ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
- // ColumnHeadersHeight = 50;
- // //设置标题内容居中显示;
- // ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
- //// RowHeadersDefaultCellStyle.Alignment =DataGridViewCellStyle;
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
- AllowUserToAddRows = false;
- AllowUserToDeleteRows = false;
- dataGridViewCellStyle1.BackColor = System.Drawing.Color.LightCyan;
- AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
- BackgroundColor = System.Drawing.Color.White;
- BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
- ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
- dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223, 240
- dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(43, 108, 150);//标题背景色
- dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
- dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White; //标题文字色
- dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
- dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
- ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
- ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
- this.ColumnHeadersHeight = 24;
- EnableHeadersVisualStyles = false;
- GridColor = System.Drawing.SystemColors.GradientInactiveCaption;
- //ReadOnly = true;
- RowHeadersVisible = false;
- RowTemplate.Height = 23;
- RowTemplate.ReadOnly = true;
- }
- catch { }
- }
- /// <summary>
- ///
- /// </summary>
- protected override void CreateHandle()
- {
- if (!IsHandleCreated)
- {
- try
- { base.CreateHandle(); }
- catch { }
- finally
- {
- if (!IsHandleCreated)
- { base.RecreateHandle(); }
- }
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void DataGridViewEx_Paint(object sender, PaintEventArgs e)
- {
- try
- {
- Pen p = new Pen(LYFZ.ComponentLibrary.GetUIResources.DataGridViewExBorderColor);
- // p.Color = LYFZ.ComponentLibrary.GetUIResources.DataGridViewExBorderColor;
- e.Graphics.DrawRectangle(p, new Rectangle(0, 0, this.Width - 1, this.Height - 1));
- }
- catch
- { }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void DataGridViewEx_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
- { SaveGridViewDisplayIndex(); }
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void cmsGridViewDisplayMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
- {
- System.Windows.Forms.ToolStripMenuItem item = (System.Windows.Forms.ToolStripMenuItem)e.ClickedItem;
- item.Checked = !item.Checked;
- this.Columns[item.Text].Visible = item.Checked;
- string tempValue = LYFZ.WinAPI.CustomPublicMethod.GetColumnDisplayString(this.Columns);
- string _GridViewUniquelyIdentify = GridViewUniquelyIdentify;
- LYFZ.ComponentLibrary.FrmLoadHandling.LoadDoWorkMethod(delegate(object obj, BackgroundWorker backgroundWorker)
- {
- try
- {
- LYFZ.Model.Model_GridViewDisplayIndex model = LYFZ.DAL.DAL_GridViewDisplayIndex.GetGridViewDisplayIndexModel
- (LYFZ.BLL.BLL_ErpUser.UsersModel.User_Account, _GridViewUniquelyIdentify);
- model.DisplayIndexValue = tempValue;
- LYFZ.DAL.DAL_GridViewDisplayIndex.SaveGridViewDisplayIndex(model);
- }
- catch
- { }
- });
- // MessageBoxCustom.Show(tempValue);
- //throw new NotImplementedException();
- }
- /// <summary>
- /// 数据是否完成邦定
- /// </summary>
- bool isCompleteBonding = false;
- /// <summary>
- /// 数据是否完成邦定
- /// </summary>
- public bool IsCompleteBonding
- {
- get { return isCompleteBonding; }
- set { isCompleteBonding = value; }
- }
- //创建一个委托,是为访问DataGridVie控件服务的。
- public delegate void UpdateDataGridView();
- /// <summary>
- /// 清空所有行
- /// </summary>
- public void ClearAllRows()
- {
- System.Data.DataTable dtble = (System.Data.DataTable)this.DataSource;
- if (dtble != null)
- { dtble.Rows.Clear(); }
- }
- /// <summary>
- /// 邦定数据源
- /// </summary>
- /// <param name="ds"></param>
- /// <param name="sortModel"></param>
- /// <param name="cmsGridViewDisplayMenu"></param>
- /// <param name="isDisplayID"></param>
- /// <param name="hiddenFields">隐藏字段例表,多个时用“,”号分隔</param>
- public void DataGridViewBind(System.Data.DataSet ds, SortedColumnModel sortModel, System.Windows.Forms.ContextMenuStrip cmsGridViewDisplayMenu = null, bool isDisplayID = false, string hiddenFields = "")
- {
- if (ds != null)
- {
- try
- {
- LYFZ.Model.Model_GridViewDisplayIndex gDindexModel = LYFZ.DAL.DAL_GridViewDisplayIndex.GetGridViewDisplayIndexModel
- (LYFZ.BLL.BLL_ErpUser.UsersModel.User_Account, this.GridViewUniquelyIdentify);
- this.Invoke(new UpdateDataGridView(delegate()
- {
- if (this.ColumnHeadersHeight <= 30)
- { this.ColumnHeadersHeight = 30; }
- this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
- this.IsCompleteBonding = false;
- this.DataSource = ds.Tables[0];
- try
- {
- this.Columns["rowId"].Visible = false;
- this.Columns["id"].Visible = isDisplayID;
- }
- catch
- { }
- ////this.SetSort(sortModel.ColumnName, sortModel.Direction);
- this.SetColumnDisplayIndex(gDindexModel.DisplayIndexValue, cmsGridViewDisplayMenu, hiddenFields);
- isCompleteBonding = true;
- }));
- }
- catch
- { }
- }
- }
- /// <summary>
- /// 显示标题菜单
- /// </summary>
- System.Windows.Forms.ContextMenuStrip displayTitleMenu = null;
- /// <summary>
- /// 设置字段显示序顺序和隐藏不显示字段
- /// </summary>
- public void SetColumnDisplayIndex(string _displayIndexValueStr, System.Windows.Forms.ContextMenuStrip cmsGridViewDisplayMenu = null, string hiddenFields = "")
- {
- try
- {
- isCompleteBonding = false;
- if (cmsGridViewDisplayMenu != null)
- {
- if (this.displayTitleMenu == null)
- {
- this.displayTitleMenu = cmsGridViewDisplayMenu;
- this.displayTitleMenu.ItemClicked += cmsGridViewDisplayMenu_ItemClicked;
- }
- }
- try
- { this._DisplayIndexValue = _displayIndexValueStr; }
- catch
- { }
- LYFZ.WinAPI.CustomPublicMethod.SetColumnDisplayIndex(this._DisplayIndexValue, this.Columns, this.displayTitleMenu, hiddenFields);
- }
- catch
- { }
- }
- /// <summary>
- /// 设置排序
- /// </summary>
- /// <param name="columnName"></param>
- /// <param name="direction"></param>
- public void SetSort(string columnName, ListSortDirection direction)
- { this.Sort(this.Columns[columnName], direction); }
- string _DisplayIndexValue = "";
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void DataGridViewEx_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
- { SaveGridViewDisplayIndex(); }
- /// <summary>
- ///
- /// </summary>
- void SaveGridViewDisplayIndex()
- {
- try
- {
- if (isCompleteBonding)
- {
- string tempValue = LYFZ.WinAPI.CustomPublicMethod.GetColumnDisplayString(this.Columns);
- if (!this._DisplayIndexValue.Equals(tempValue))
- {
- this._DisplayIndexValue = tempValue;
- string _GridViewUniquelyIdentify = this.GridViewUniquelyIdentify;
- if (gridViewUniquelyIdentify.Trim() == "")
- {
- MessageBoxCustom.Show("DataGridView的唯一标识 GridViewUniquelyIdentify 值不能为空");
- return;
- }
- LYFZ.ComponentLibrary.FrmLoadHandling.LoadDoWorkMethod(delegate(object obj, BackgroundWorker backgroundWorker)
- {
- try
- {
- LYFZ.Model.Model_GridViewDisplayIndex model = LYFZ.DAL.DAL_GridViewDisplayIndex.GetGridViewDisplayIndexModel
- (LYFZ.BLL.BLL_ErpUser.UsersModel.User_Account, _GridViewUniquelyIdentify);
- model.DisplayIndexValue = _DisplayIndexValue;
- LYFZ.DAL.DAL_GridViewDisplayIndex.SaveGridViewDisplayIndex(model);
- }
- catch
- { }
- });
- }
- }
- }
- catch
- { }
- }
- string gridViewUniquelyIdentify = "";
- /// <summary>
- /// GridViewUniquelyIdentify唯一标识不能为空
- /// </summary>
- public string GridViewUniquelyIdentify
- {
- get { return gridViewUniquelyIdentify; }
- set
- {
- try
- {
- try
- { gridViewUniquelyIdentify = value + "_" + this.Parent.Name + "_" + this.Name; }
- catch
- { gridViewUniquelyIdentify = value + "_" + this.Name; }
- }
- catch
- { gridViewUniquelyIdentify = value; }
- }
- }
- /// <summary>
- /// 获取排序对象 请在邦定数据前获取
- /// </summary>
- /// <param name="defaultSortField"></param>
- /// <param name="defaultSortDirection"></param>
- /// <returns></returns>
- public SortedColumnModel GetSortedColumnModel(string defaultSortField = "id", ListSortDirection defaultSortDirection = ListSortDirection.Descending)
- {
- SortedColumnModel model = new SortedColumnModel();
- try
- {
- DataGridViewColumn sortColumn = this.SortedColumn;
- string orderStr = " " + defaultSortField + " desc ";
- string columnName = defaultSortField;
- if (defaultSortDirection == ListSortDirection.Descending)
- { orderStr = " " + defaultSortField + " desc "; }
- else
- { orderStr = " " + defaultSortField + " asc "; }
- ListSortDirection Direction = defaultSortDirection;
- if (sortColumn != null)
- {
- columnName = sortColumn.Name;
- switch (this.SortOrder)
- {
- case SortOrder.Ascending:
- orderStr = "[" + sortColumn.Name + "] asc ";
- Direction = ListSortDirection.Ascending;
- break;
- case SortOrder.Descending:
- orderStr = "[" + sortColumn.Name + "] desc ";
- Direction = ListSortDirection.Descending;
- break;
- default: break;
- }
- }
- model.Direction = Direction;
- model.OrderStr = orderStr.Trim();
- model.SortColumn = sortColumn;
- model.ColumnName = columnName;
- }
- catch { }
- return model;
- }
- /// <summary>
- /// 导出数据
- /// </summary>
- public void ExportDataTable()
- {
- DataGridViewExport.DataToExcel(this);
- }
- /// <summary>
- /// 导出数据
- /// </summary>
- public void DataToExcelPayroll(string StrExeclName = "")
- {
- DataGridViewExport.DataToExcelPayroll(this, StrExeclName);
- }
- /// <summary>
- /// 排序对象
- /// </summary>
- public class SortedColumnModel
- {
- public SortedColumnModel()
- { }
- DataGridViewColumn sortColumn = new DataGridViewColumn();
- /// <summary>
- /// 当前的排序字段,请在邦定数据前获取
- /// </summary>
- public DataGridViewColumn SortColumn
- {
- get { return sortColumn; }
- set { sortColumn = value; }
- }
- string orderStr = " id desc ";
- /// <summary>
- /// 获取排序字符串
- /// </summary>
- public string OrderStr
- {
- get { return orderStr; }
- set { orderStr = value; }
- }
- string columnName = "id";
- /// <summary>
- /// 排序字段名
- /// </summary>
- public string ColumnName
- {
- get { return columnName; }
- set { columnName = value; }
- }
- ListSortDirection direction = ListSortDirection.Descending;
- /// <summary>
- /// 排序方式
- /// </summary>
- public ListSortDirection Direction
- {
- get { return direction; }
- set { direction = value; }
- }
- }
- }
- #region
- public class DataGridViewExport
- {
- /// <summary>
- /// 导出DataGridView数据 以文本形式导出
- /// </summary>
- /// <param name="m_DataView"></param>
- public static void DataTableToExcel(DataTable m_DataView, bool IsShowSave = true, string StrFileName = "", string ExportOKPrompt = "")
- {
- string FileName = "";
- if (IsShowSave)
- {
- SaveFileDialog saveFile = new SaveFileDialog();
- saveFile.Title = "导出数据报表文件";
- saveFile.Filter = "EXECL文件(*.xls) |*.xls |文本文件(*.txt) |*.txt |所有文件(*.*) |*.*";
- saveFile.FilterIndex = 1;
- DialogResult drst = saveFile.ShowDialog();
- if (drst == DialogResult.No || drst == DialogResult.Cancel || drst == DialogResult.No || drst == DialogResult.Abort)
- { return; }
- FileName = saveFile.FileName;
- }
- else
- { FileName = StrFileName; }
- //定义表格内数据的行数和列数
- int rowscount = m_DataView.Rows.Count;
- int colscount = m_DataView.Columns.Count;
- //行数必须大于0 列数必须大于0
- if (rowscount <= 0 || colscount <= 0)
- {
- MessageBoxCustom.Show("没有数据可供保存 ");
- return;
- }
- //行数不可以大于65536
- if (rowscount > 65536)
- {
- MessageBoxCustom.Show("数据记录数太多(最多不能超过65536条),不能保存 ");
- return;
- }
- //列数不可以大于255
- if (colscount > 255)
- {
- MessageBoxCustom.Show("数据记录列数太多,不能保存 ");
- return;
- }
- if (File.Exists(FileName))
- File.Delete(FileName);
- FileStream objFileStream;
- StreamWriter objStreamWriter;
- string strLine = "";
- objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
- objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
- for (int i = 0; i < m_DataView.Columns.Count; i++)
- {
- strLine = strLine + m_DataView.Columns[i].ColumnName.Trim() + Convert.ToChar(9);
- }
- objStreamWriter.WriteLine(strLine);
- strLine = "";
- for (int i = 0; i < m_DataView.Rows.Count; i++)
- {
- for (int j = 0; j < m_DataView.Columns.Count; j++)
- {
- if (m_DataView.Rows[i][j].ToString().Trim() == null)
- strLine = strLine + " " + Convert.ToChar(9);
- else
- {
- string rowstr = "";
- rowstr = m_DataView.Rows[i][j].ToString().Trim();
- rowstr = rowstr.Replace("\r\n", " ");
- rowstr = rowstr.Replace("\t", " ");
- rowstr = rowstr.Replace("\r", " ");
- rowstr = rowstr.Replace("\n", " ");
- rowstr = rowstr.Trim();
- try
- {
- string tempValue = rowstr.Split(',')[0].Trim();
- if (tempValue.Length == 11)
- {
- long tempI = 0;
- if (long.TryParse(tempValue, out tempI))
- { rowstr = "'" + rowstr; }
- }
- }
- catch
- { }
- strLine = strLine + rowstr + Convert.ToChar(9);
- }
- }
- objStreamWriter.WriteLine(strLine);
- strLine = "";
- }
- objStreamWriter.Close();
- objFileStream.Close();
- if (string.IsNullOrEmpty(ExportOKPrompt))
- { MessageBoxCustom.Show("导出成功"); }
- else
- { MessageBoxCustom.Show(ExportOKPrompt); }
- }
- /// <summary>
- /// 导出DataGridView数据 以文本形式导出
- /// </summary>
- /// <param name="m_DataView"></param>
- public static void DataToExcel(DataGridView m_DataView)
- {
- SaveFileDialog saveFile = new SaveFileDialog();
- saveFile.Title = "导出数据报表文件";
- saveFile.Filter = "EXECL文件(*.xls) |*.xls |文本文件(*.txt) |*.txt |所有文件(*.*) |*.*";
- saveFile.FilterIndex = 1;
- if (saveFile.ShowDialog() == DialogResult.OK)
- {
- //定义表格内数据的行数和列数
- int rowscount = m_DataView.Rows.GetRowCount(DataGridViewElementStates.Visible);
- int colscount = m_DataView.Columns.GetColumnCount(DataGridViewElementStates.Visible);
- //行数必须大于0 列数必须大于0
- if (rowscount <= 0 || colscount <= 0)
- {
- MessageBoxCustom.Show("没有数据可供保存 ");
- return;
- }
- //行数不可以大于65536
- if (rowscount > 65536)
- {
- MessageBoxCustom.Show("数据记录数太多(最多不能超过65536条),不能保存 ");
- return;
- }
- //列数不可以大于255
- if (colscount > 255)
- {
- MessageBoxCustom.Show("数据记录列数太多,不能保存 ");
- return;
- }
- string FileName = saveFile.FileName;
- try
- {
- if (LYFZ.WinAPI.CustomPublicMethod.DataGridViewToExcel(FileName, m_DataView))
- {
- MessageBoxCustom.Show("导出成功");
- }
- else
- {
- MessageBoxCustom.Show("导出失败,请重试!");
- }
- }
- catch (Exception ex)
- {
- MessageBoxCustom.Show("导出失败,原因:" + ex.Message);
- }
- }
- }
- /// <summary>
- /// 导出DataGridView数据 以文本形式导出(只用于工资管理)
- /// </summary>
- /// <param name="m_DataView"></param>
- public static void DataToExcelPayroll(DataGridView m_DataView, string StrExeclName)
- {
- SaveFileDialog saveFileDialog = new SaveFileDialog();
- saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
- saveFileDialog.FilterIndex = 0;
- saveFileDialog.RestoreDirectory = true;
- saveFileDialog.CreatePrompt = true;
- saveFileDialog.FileName = StrExeclName;
- saveFileDialog.Title = "保存为Excel文件";
- saveFileDialog.CreatePrompt = false;
- saveFileDialog.OverwritePrompt = true;
- saveFileDialog.ShowDialog();
- Stream myStream;
- if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"
- myStream = saveFileDialog.OpenFile();
- StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
- string str = "";
- Cursor.Current = Cursors.WaitCursor;
- try
- {
- //写标题
- for (int i = 0; i < m_DataView.ColumnCount; i++)
- {
- if (m_DataView.Columns[i].Visible)
- {
- if (i > 0)
- { str += "\t"; }
- str += m_DataView.Columns[i].HeaderText;
- }
- }
- sw.WriteLine(str);
- //写所有内容
- decimal decAllAmount = 0;
- for (int j = 0; j < m_DataView.Rows.Count; j++)
- {
- decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
- PaintedColumn(m_DataView, j, sw);
- }
- sw.WriteLine("总计:" + decAllAmount.ToString("n2"));
- sw.WriteLine("\r\n");
- sw.WriteLine("******以下为分类统计******");
- sw.WriteLine("\r\n");
- string StrSortColumnName = "Column8";// "Column17";
- m_DataView.Sort(m_DataView.Columns[StrSortColumnName], ListSortDirection.Ascending);
- decAllAmount = 0;
- string StrSortName = "";
- DataTable dt_tbl = new DataTable();
- for (int i = 0; i < m_DataView.Columns.Count; i++)
- {
- if (m_DataView.Columns[i].Visible)
- { dt_tbl.Columns.Add(m_DataView.Columns[i].Name.Trim(), typeof(string)); }
- }
- for (int j = 0; j < m_DataView.Rows.Count; j++)
- {
- switch (m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim())
- {
- case "全款":
- case "预约收款":
- case "预约补款":
- DataRow newRow = dt_tbl.NewRow();
- for (int i = 0; i < m_DataView.Columns.Count; i++)
- {
- try
- {
- if (m_DataView.Columns[i].Visible)
- {
- if (m_DataView.Rows[j].Cells[i].Value != null)
- { newRow[m_DataView.Columns[i].Name] = m_DataView.Rows[j].Cells[i].Value.ToString().Trim(); }
- else
- { newRow[m_DataView.Columns[i].Name] = ""; }
- }
- }
- catch
- { }
- }
- dt_tbl.Rows.Add(newRow);
- break;
- default:
- if (j == 0)
- {
- StrSortName = m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim();
- decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
- PaintedColumn(m_DataView, j, sw);
- }
- else
- {
- if (m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim() == m_DataView.Rows[j - 1].Cells[StrSortColumnName].Value.ToString().Trim())
- {
- PaintedColumn(m_DataView, j, sw);
- }
- else
- {
- sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
- StrSortName = "";
- decAllAmount = 0;
- sw.WriteLine("\r\n");
- PaintedColumn(m_DataView, j, sw);
- }
- StrSortName = m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim();
- decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
- }
- break;
- }
- }
- sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
- sw.WriteLine("\r\n");
- decAllAmount = 0;
- dt_tbl.DefaultView.Sort = StrSortColumnName + " ASC";
- for (int j = 0; j < dt_tbl.Rows.Count; j++)
- {
- if (j == 0)
- {
- try
- { StrSortName = dt_tbl.Rows[j][StrSortColumnName].ToString().Trim(); }
- catch { }
- decAllAmount += Convert.ToDecimal(dt_tbl.Rows[j]["Column3"]);
- PaintedColumn(dt_tbl, j, sw);
- }
- else
- {
- if (dt_tbl.Rows[j][StrSortColumnName].ToString().Trim() == dt_tbl.Rows[j - 1][StrSortColumnName].ToString().Trim())
- {
- PaintedColumn(dt_tbl, j, sw);
- }
- else
- {
- sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
- StrSortName = "";
- decAllAmount = 0;
- sw.WriteLine("\r\n");
- PaintedColumn(dt_tbl, j, sw);
- }
- StrSortName = dt_tbl.Rows[j][StrSortColumnName].ToString().Trim();
- decAllAmount += Convert.ToDecimal(dt_tbl.Rows[j]["Column3"]);
- }
- }
- sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
- sw.Close();
- myStream.Close();
- MessageBoxCustom.Show("导出完毕!");
- }
- catch (Exception l)
- { MessageBox.Show(l.ToString()); }
- finally
- {
- sw.Close();
- myStream.Close();
- }
- }
- static void PaintedColumn(DataGridView m_DataView, int RowI, StreamWriter sw)
- {
- string tempStr = "";
- for (int k = 0; k < m_DataView.ColumnCount; k++)
- {
- if (m_DataView.Columns[k].Visible)
- {
- if (k > 0)
- { tempStr += "\t"; }
- if (m_DataView.Rows[RowI].Cells[k].Value != null)
- { tempStr += m_DataView.Rows[RowI].Cells[k].Value.ToString(); }
- else
- { tempStr += ""; }
- }
- }
- sw.WriteLine(tempStr);
- }
- static void PaintedColumn(DataTable dt_DataView, int RowI, StreamWriter sw)
- {
- string tempStr = "";
- for (int k = 0; k < dt_DataView.Columns.Count; k++)
- {
- if (k > 0)
- { tempStr += "\t"; }
- if (dt_DataView.Rows[RowI][k] != null && !string.IsNullOrEmpty(dt_DataView.Rows[RowI][k].ToString().Trim()))
- { tempStr += dt_DataView.Rows[RowI][k].ToString(); }
- else
- { tempStr += ""; }
- }
- sw.WriteLine(tempStr);
- }
- }
- #endregion
- }
|