heyu52 发布留言 2008-4-12 14:39 很好看的和功能强大的 DataGridViewusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using HVS.WinUI.Forms; namespace HVS.WinUI.Components { public partial class GridView : DataGridView { #region 公共变量 Button btnLeft = new Button(); private ContextMenuStrip HeaderColumnMenuStrip; private ToolStripMenuItem HiddenColumn; private ToolStripMenuItem IncreasingColumn; private ToolStripMenuItem DecreasingColumn; private ToolStripMenuItem RemovalOrder; private ToolStripMenuItem Autoadjustcolumn; string CurrentColumnName = "";//获取单击时的列名 Point point = Point.Empty; private ToolStripSeparator toolStripSeparator1; private ToolStripMenuItem EnquiryColumn; private ToolStripSeparator toolStripSeparator2; private ToolStripMenuItem FixedColumn;//获取单击时的绝对坐标 private List _columnLookups = new List(); private Dictionary _columnsWithLookup; private bool _isRetureLookUpColumn = false; Dictionary Columus = new Dictionary(); LookUp Lookup = new LookUp();
bool _allowUserToOrderColumns = true;
#endregion
#region 属性 [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [Category("HVS")] public List ColumnLookups { get { return _columnLookups; } set { _columnLookups = value; } }
[DefaultValue(true)] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [Category("HVS")] public new bool AllowUserToOrderColumns { get { return _allowUserToOrderColumns; } set { _allowUserToOrderColumns = value; } }
#endregion
#region 事件 public delegate void CancelLookupEventHandler(object sender, CancelLookupEventArgs e); public delegate void LookupEventHandler(object sender, LookupEventArgs e);
public event CancelLookupEventHandler BeforeLookup; public event LookupEventHandler AfterLookup; LookupEventArgs AfterLookupArgs = new LookupEventArgs(); #endregion
#region 构造函数 private System.ComponentModel.IContainer components = null;
private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.HeaderColumnMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.EnquiryColumn = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.HiddenColumn = new System.Windows.Forms.ToolStripMenuItem(); this.FixedColumn = new System.Windows.Forms.ToolStripMenuItem(); this.Autoadjustcolumn = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.IncreasingColumn = new System.Windows.Forms.ToolStripMenuItem(); this.DecreasingColumn = new System.Windows.Forms.ToolStripMenuItem(); this.RemovalOrder = new System.Windows.Forms.ToolStripMenuItem(); this.HeaderColumnMenuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); this.SuspendLayout(); // // HeaderColumnMenuStrip // this.HeaderColumnMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.EnquiryColumn, this.toolStripSeparator2, this.HiddenColumn, this.FixedColumn, this.Autoadjustcolumn, this.toolStripSeparator1, this.IncreasingColumn, this.DecreasingColumn, this.RemovalOrder}); this.HeaderColumnMenuStrip.Name = "contextMenuStrip1"; this.HeaderColumnMenuStrip.Size = new System.Drawing.Size(143, 170); // // EnquiryColumn // this.EnquiryColumn.Name = "EnquiryColumn"; this.EnquiryColumn.Size = new System.Drawing.Size(142, 22); this.EnquiryColumn.Text = "查询"; this.EnquiryColumn.Click += new System.EventHandler(this.EnquiryColumn_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(139, 6); // // HiddenColumn // this.HiddenColumn.Name = "HiddenColumn"; this.HiddenColumn.Size = new System.Drawing.Size(142, 22); this.HiddenColumn.Text = "隐藏此列"; this.HiddenColumn.Click += new System.EventHandler(this.HiddenColumn_Click); // // FixedColumn // this.FixedColumn.Name = "FixedColumn"; this.FixedColumn.Size = new System.Drawing.Size(142, 22); this.FixedColumn.Text = "固定列"; this.FixedColumn.Click += new System.EventHandler(this.FixedColumn_Click); // // Autoadjustcolumn // this.Autoadjustcolumn.Name = "Autoadjustcolumn"; this.Autoadjustcolumn.Size = new System.Drawing.Size(142, 22); this.Autoadjustcolumn.Text = "自动调整列宽"; this.Autoadjustcolumn.Click += new System.EventHandler(this.Autoadjustcolumn_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(139, 6); // // IncreasingColumn // this.IncreasingColumn.Name = "IncreasingColumn"; this.IncreasingColumn.Size = new System.Drawing.Size(142, 22); this.IncreasingColumn.Text = "递增排列"; this.IncreasingColumn.Click += new System.EventHandler(this.IncreasingColumn_Click); // // DecreasingColumn // this.DecreasingColumn.Name = "DecreasingColumn"; this.DecreasingColumn.Size = new System.Drawing.Size(142, 22); this.DecreasingColumn.Text = "递减排列"; this.DecreasingColumn.Click += new System.EventHandler(this.DecreasingColumn_Click); // // RemovalOrder // this.RemovalOrder.Name = "RemovalOrder"; this.RemovalOrder.Size = new System.Drawing.Size(142, 22); this.RemovalOrder.Text = "清除排列"; this.RemovalOrder.Click += new System.EventHandler(this.RemovalOrder_Click); // // GridView // this.RowTemplate.Height = 23; this.HeaderColumnMenuStrip.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); this.ResumeLayout(false);
}
public GridView() : base() { InitializeComponent(); _columnsWithLookup = new Dictionary(); }
public GridView(IContainer container) { container.Add(this);
InitializeComponent(); } #endregion
#region GridView protected override void InitLayout() { base.InitLayout(); if (!DesignMode) { InitializeColumnsLookup(); btnLeft.Location = new Point(1, 1); btnLeft.Text = "显示"; btnLeft.Size = new Size(this.RowHeadersWidth - 1, 25); if (!DesignMode) btnLeft.Click += new EventHandler(btnLeft_Click); this.Controls.Add(btnLeft); } }
void btnLeft_Click(object sender, EventArgs e) { Dictionary columnsName = new Dictionary(); foreach (DataGridViewColumn column in this.Columns) { columnsName.Add(column.Name, column.Visible); }
Point loc = new Point(); loc = FindFormLocation(this); Point selPoint = new Point();
if (FindFormType()) selPoint = new Point(loc.X + this.Left, loc.Y + this.Top + SystemInformation.CaptionHeight); else selPoint = new Point(loc.X + this.Left, loc.Y + this.Top + SystemInformation.CaptionHeight + 68 + SystemInformation.MenuHeight);
SelectColumnForm selectColumnForm = new SelectColumnForm(columnsName, selPoint);
selectColumnForm.TopMost = true; selectColumnForm.ShowDialog();
foreach (DataGridViewColumn column in this.Columns) { column.Visible = SelectColumnForm.IsColumnCheck[column.Name]; } }
protected override void OnCreateControl() {
base.OnCreateControl();
#region 样式外观
//去掉默认的样式外观 this.EnableHeadersVisualStyles = false;
this.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(247, 246, 239); this.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Raised; this.ColumnHeadersHeight = 26; this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.ColumnHeadersDefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; this.ColumnHeadersDefaultCellStyle.ForeColor = System.Drawing.SystemColors.WindowText; this.ColumnHeadersDefaultCellStyle.SelectionBackColor = System.Drawing.SystemColors.Highlight; this.ColumnHeadersDefaultCellStyle.SelectionForeColor = System.Drawing.SystemColors.HighlightText; this.RowHeadersDefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; this.RowHeadersDefaultCellStyle.BackColor = System.Drawing.SystemColors.Window; this.RowHeadersDefaultCellStyle.ForeColor = System.Drawing.SystemColors.WindowText; this.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; this.DefaultCellStyle.SelectionBackColor = Color.Wheat; this.DefaultCellStyle.SelectionForeColor = Color.DarkSlateBlue; this.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; this.GridColor = System.Drawing.SystemColors.GradientActiveCaption; this.BackgroundColor = System.Drawing.SystemColors.Window; this.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; FixedColumn.Checked = false;
#endregion
}
//获取点击的列名 protected override void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e) { base.OnColumnHeaderMouseClick(e); if (e.X + this.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Left > this.RowHeadersWidth && e.Y < ColumnHeadersHeight) { //point = new Point(e.X + this.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Left, e.Y);
#region Checked try { if (this.SortedColumn.Name == CurrentColumnName) { if (this.SortOrder == SortOrder.Ascending) { this.IncreasingColumn.Checked = true; this.DecreasingColumn.Checked = false; this.RemovalOrder.Checked = false; } else if (this.SortOrder == SortOrder.Descending) { this.IncreasingColumn.Checked = false; this.DecreasingColumn.Checked = true; this.RemovalOrder.Checked = false; } else if (this.SortOrder == SortOrder.None && this.Columns[CurrentColumnName].SortMode == DataGridViewColumnSortMode.NotSortable) { this.IncreasingColumn.Checked = false; this.DecreasingColumn.Checked = false; this.RemovalOrder.Checked = true; } } else { this.IncreasingColumn.Checked = false; this.DecreasingColumn.Checked = false; this.RemovalOrder.Checked = false; } } catch { this.IncreasingColumn.Checked = false; this.DecreasingColumn.Checked = false; this.RemovalOrder.Checked = false; } #endregion } }
//主要弹出右击菜单 protected override void OnMouseClick(MouseEventArgs e) {
System.Windows.Forms.DataGridView.HitTestInfo hti = this.HitTest(e.X, e.Y); try { CurrentColumnName = this.Columns[hti.ColumnIndex].Name; } catch {
}
if (e.Button == MouseButtons.Right) { foreach (Control con in this.Controls) if (con == btnLeft) continue; else if (con is Button) con.Dispose(); if (hti.Type == DataGridViewHitTestType.ColumnHeader) { this.HeaderColumnMenuStrip.Show(this, e.Location); } else if (hti.Type == DataGridViewHitTestType.TopLeftHeader) { //左上角的单元格 } }
base.OnMouseClick(e); }
bool FindFormType() { if (this.Parent is LookupForm) return true; else return false; }
Point FindFormLocation(Control control) { if (control.Parent is Form) { if (((Form)control.Parent).IsMdiChild) { return new Point(((Form)control.Parent).ParentForm.Left, ((Form)control.Parent).ParentForm.Top); } else { return new Point(control.Parent.Left, control.Parent.Top); } } else { return FindFormLocation(control.Parent); } }
#endregion
#region 释放资源
public virtual void ReleaseResources() {
}
private void PerformReleaseResources() {
}
protected override void Dispose(bool disposing) { if (disposing) { try { PerformReleaseResources(); } catch {
}
if (components != null) { components.Dispose(); } } base.Dispose(disposing); }
#endregion
#region lookup
public void ResetColumnLookups() { if (this._columnLookups == null) this._columnLookups = new List(); else this._columnLookups.Clear(); }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void InitializeColumnsLookup() { if (DesignMode) return; if (ColumnLookups.Count == 0) return; DataGridViewColumn col = null; _columnsWithLookup = new Dictionary(); foreach (ColumnLookup columnLookup in this.ColumnLookups) { if (!this.Columns.Contains(columnLookup.ColumnKey)) continue;
col = this.Columns[columnLookup.ColumnKey];
if (_columnsWithLookup.ContainsKey(col)) _columnsWithLookup[col] = (LookUp)columnLookup; else _columnsWithLookup.Add(col, (LookUp)columnLookup); } }
protected override void OnCellEnter(DataGridViewCellEventArgs e) { foreach (Control con in this.Controls) if (con == btnLeft) continue; else if (con is Button) con.Dispose(); base.OnCellEnter(e); if (_columnsWithLookup == null) return; foreach (DataGridViewColumn col in _columnsWithLookup.Keys) { if (col.Name == this.Columns[e.ColumnIndex].Name) { Lookup = _columnsWithLookup[col]; if (string.IsNullOrEmpty(Lookup.SQL)) return; Button btn = new Button(); btn.Text = "..."; btn.Font = new Font("Arial", 7); btn.Visible = true; btn.Width = this.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Height; btn.Height = this.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Height; this.Controls.Add(btn); btn.Location = new System.Drawing.Point((this.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true) .Right - btn.Width), this.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Y); btn.Click -= new EventHandler(btn_Click); btn.Click += new EventHandler(btn_Click); return; } } }
void btn_Click(object sender, EventArgs e) { btn_LookUp(sender, new CancelLookupEventArgs()); Application.DoEvents(); }
public void btn_LookUp(object sender, CancelLookupEventArgs e) { #region BeforeLookup if (BeforeLookup != null) { BeforeLookup(sender, e); if (e.Cancel == true)//beforelookup前进行取消 { this.SelectAll(); return; } } #endregion
#region Lookup if (!string.IsNullOrEmpty(Lookup.SQL)) { //try //{ DataTable table = new DataTable();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); cmd.CommandText = Lookup.SQL; System.Data.SqlClient.SqlDataAdapter adp = new System.Data.SqlClient.SqlDataAdapter(cmd.CommandText, HVS.Common.Shared.sqlConnection); DataSet ds = new DataSet(); adp.Fill(ds); DataTable newtable = new System.Data.DataTable(); Columus.Clear(); foreach (DataColumn co in ds.Tables[0].Columns) { DataColumn col = new DataColumn(co.ColumnName, co.DataType); col.ReadOnly = true; newtable.Columns.Add(col); Columus.Add(co.ColumnName, co.ColumnName); if (!_isRetureLookUpColumn && !string.IsNullOrEmpty(Lookup.ReturnColumn)) { if (co.ColumnName == Lookup.ReturnColumn) { _isRetureLookUpColumn = true;//如果指定的列合法 } }
} foreach (DataRow row in ds.Tables[0].Rows) { object[] value = new object[row.Table.Columns.Count]; for (int i = 0; i < row.Table.Columns.Count; i++) value; newtable.Rows.Add(value); } LookupForm lookupForm = new LookupForm(newtable, Columus); if (_isRetureLookUpColumn) lookupForm.ReturnColumn = Lookup.ReturnColumn;//返回指定行的指定列 else lookupForm.ReturnColumn = "";//返回当前行第一列
lookupForm.TopMost = true; lookupForm.ShowDialog(); if (LookupForm.IsSelectRow) { this.CurrentCell.Value = lookupForm.ReturnValue;
AfterLookupArgs.LookUpSelectRow = lookupForm.LookUpSelectRow; }
// this.Focus(); //} //catch //{ // MessageBox.Show("失败"); // this.Text = ""; // this.Focus(); // this.SelectionStart = this.Text.Length; // AfterLookupArgs.LookUpSelectRow = null; // return; //} } #endregion
#region AfterLookup if (AfterLookup != null && LookupForm.IsSelectRow) { AfterLookup(sender, AfterLookupArgs);
} #endregion }
protected override void OnCellLeave(DataGridViewCellEventArgs e) { base.OnCellLeave(e); foreach (Control con in this.Controls) if (con == btnLeft) continue; else if (con is Button) con.Dispose(); }
#endregion
#region 标题菜单
private void HiddenColumn_Click(object sender, EventArgs e) { this.Columns[CurrentColumnName].Visible = false; this.ContextMenuStrip = null; }
private void EnquiryColumn_Click(object sender, EventArgs e) {
}
private void DecreasingColumn_Click(object sender, EventArgs e) { this.Columns[CurrentColumnName].SortMode = DataGridViewColumnSortMode.Automatic; this.Sort(this.Columns[CurrentColumnName], ListSortDirection.Descending); }
private void IncreasingColumn_Click(object sender, EventArgs e) { this.Columns[CurrentColumnName].SortMode = DataGridViewColumnSortMode.Automatic; this.Sort(this.Columns[CurrentColumnName], ListSortDirection.Ascending); }
private void FixedColumn_Click(object sender, EventArgs e) { FixedColumn.Checked = !FixedColumn.Checked; this.AllowUserToOrderColumns = !FixedColumn.Checked; }
private void RemovalOrder_Click(object sender, EventArgs e) { this.Columns[CurrentColumnName].SortMode = DataGridViewColumnSortMode.NotSortable; }
private void Autoadjustcolumn_Click(object sender, EventArgs e) {
}
#endregion
}
#region SelectColumnForm
public partial class SelectColumnForm : Form {
private System.ComponentModel.IContainer components = null; private System.Windows.Forms.CheckedListBox checkedListColumns; Point point = Point.Empty;
public static Dictionary IsColumnCheck = new Dictionary();
private void InitializeComponent() { this.checkedListColumns = new System.Windows.Forms.CheckedListBox(); this.SuspendLayout(); // // checkedListColumns // this.checkedListColumns.Dock = System.Windows.Forms.DockStyle.Fill; this.checkedListColumns.FormattingEnabled = true; this.checkedListColumns.Items.AddRange(new object[] { "全选"}); this.checkedListColumns.Location = new System.Drawing.Point(0, 0); this.checkedListColumns.Name = "checkedListColumns"; this.checkedListColumns.Size = new System.Drawing.Size(162, 308); this.checkedListColumns.TabIndex = 0; this.checkedListColumns.SelectedValueChanged += new System.EventHandler(this.checkedListColumns_SelectedValueChanged); // // SelectColumnForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(162, 320); this.Controls.Add(this.checkedListColumns); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SelectColumnForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; // this.Location = this.point; this.Text = "选择显示列"; this.ResumeLayout(false);
}
public SelectColumnForm() { InitializeComponent(); }
public SelectColumnForm(Dictionary Columns, Point location) { point = location; InitializeComponent(); foreach (string columnName in Columns.Keys) { this.checkedListColumns.Items.Add(columnName, Columns[columnName]); } IsColumnCheck.Clear(); this.Location = this.point; }
protected override void OnFormClosing(FormClosingEventArgs e) { for (int i = 1; i < this.checkedListColumns.Items.Count; i++) IsColumnCheck.Add(checkedListColumns.Items.ToString() == "全选" && checkedListColumns.GetItemChecked(checkedListColumns.SelectedIndex)) { for (int i = 1; i < this.checkedListColumns.Items.Count; i++) checkedListColumns.SetItemChecked(i, true); } } catch { } }
protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); }
}
#endregion }
[ 本帖最后由 heyu52 于 2008-4-12 14:55 编辑 [/it]]geqmoon 发布留言 2008-4-12 14:42 牛X,强lengxiao 发布留言 2008-4-12 16:40 太强了!牛!!!!!!!!呵呵drychq 发布留言 2008-4-12 17:39 很好哦... 能发个完整的例子吗??? 代码运行不起... ychq2004@126.comhuangjojo 发布留言 2008-4-12 20:36 不错不错,最好也给我发个完整的例子,本人万分感谢!! jojohwz@163.comheyu52 发布留言 2008-4-12 20:53 VS2008我的这个是用VS2008做的,你们装了没有先chymzyl 发布留言 2008-4-24 15:26 很不错,能给个完整的例子么?请问大侠ColumnLookup是在HVS.WinUI.Forms里面定义的吗? kangfuguo@yahoo.com.cn青格儿 发布留言 2008-4-24 20:46 你真厉害! 顶一下!发个源程序吧,楼主 185548111@qq.comoutsiders 发布留言 2008-6-16 16:13 楼主真牛X。。。小弟最近要做一个这个样的东西。 楼主能不能把完整的源码发下,outsiders@citiz.net 谢谢!tomtory 发布留言 2008-6-16 17:11 LZ厉害的哦 整个源码给我的嘛 lyj_552211@163.com 2008我已经装上了zsyutian 发布留言 2008-6-17 08:34 希望把源码传上来大家共同提高雪雨星风 发布留言 2008-6-17 08:40 我安装了 谢楼主了 drl_0602@hotmail.comandey 发布留言 2008-6-17 09:14 无语ingpanxuguang 发布留言 2008-6-28 18:30 厉害 我也想看看整个源码 2008我已经装上 panxuguang735@163.com 谢谢啊
页: [1] 特别说明:如网页特效代码中有引用图片文件等,请自己下载到本地调试! |