阅读全文:http://www.sufeinet.com/thread-598-1-1.html
先来看看效果吧
升级报告说明
这次升级的功能主有
1.对鼠标跟随效果进行的优化
2.增加了行号的功能方便查找数据
3.增加一个菜单功能,目前里面有的功能主要是冻结和恢复首行和首列功能。还有导出Excel和全选功能。
实现说明
首先我们要准备两张图片,用来做什么呢,自然是用来做菜单使用的。我是临时整理了两张看着不怎么好看,不过功能不影响大家下载源代码后要吧自行修改的漂亮一些。
然后我们第一步要做的是怎么样把这个图片添加到DataGridView里面去。在添加这个控件 之前呢我们要做两件事情,第一就是New一个左键菜单,绑定到这个菜单Button,
第二步是给这个button注册一个单击事件看下面的代码。
#region
注册菜单项
//
在这里添加菜单项
cmsleft.Items.Add(createItem(
"
clumnsFist
"
,
"
冻结首列
"
,
new
EventHandler(clumnsFist_Click)));
cmsleft.Items.Add(createItem(
"
rowsFist
"
,
"
冻结首行
"
,
new
EventHandler(rowsFistFist_Click)));
cmsleft.Items.Add(createItem(
"
officeExeceout
"
,
"
导出到Excel
"
,
new
EventHandler(officeExeceout_Click)));
cmsleft.Items.Add(createItem(
"
fullSelect
"
,
"
全选
"
,
new
EventHandler(fullSelect_Click)));
#endregion
#region
绑定菜单
Button objpb
=
new
Button();
objpb.BackgroundImage
=
bxyztSkin.Properties.Resources.caidan;
objpb.Location
=
new
Point(objpb.Location.X
+
9
, objpb.Location.Y
+
4
);
objpb.Width
=
17
;
objpb.Text
=
""
;
//
绑定一个右键菜单
objpb.ContextMenuStrip
=
cmsleft;
objpb.Cursor
=
System.Windows.Forms.Cursors.Hand;
objpb.Height
=
17
;
objpb.BackgroundImageLayout
=
ImageLayout.Stretch;
objpb.FlatStyle
=
FlatStyle.Popup;
//
在添加前先注册一个事件
objpb.Click
+=
new
EventHandler(objpb_Click);
this
.Controls.Add(objpb);
#endregion
这样的话我们在运行这个控件时就可以看到菜单效果了,下面我们来分别对事件进行一下处理吧
1.Button单击事件
//
Button单击事件
void
objpb_Click(
object
sender, EventArgs e)
{
Button objbootn
=
(Button)sender;
//
显示菜单的位置
objbootn.ContextMenuStrip.Show(Control.MousePosition.X, Control.MousePosition.Y);
}
2.全选事件
//
全选
void
fullSelect_Click(
object
sender, EventArgs e)
{
this
.SelectAll();
}
3.导出到Excel事件
//
导出到Excel
void
officeExeceout_Click(
object
sender, EventArgs e)
{
if
(
this
.Rows.Count
>
0
)
{
OfficeManagerMentServices.DataGridViewToExcel(
this
);
}
}
OfficeManagerMentServices类如下
View Code
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Windows.Forms;
using
System.IO;
namespace
bxyztSkin.csList
{
public
class
OfficeManagerMentServices
{
///
<summary>
///
将 DataGridView的数据导出Excel
///
</summary>
///
<remarks>
///
using System.IO;
///
</remarks>
///
<param name="dgv"></param>
public
static
void
DataGridViewToExcel(bxyztSkin.Editors.CDataGridView dgv)
{
SaveFileDialog dlg
=
new
SaveFileDialog();
dlg.Filter
=
"
Execl files (*.xls)|*.xls
"
;
dlg.CheckFileExists
=
false
;
dlg.CheckPathExists
=
false
;
dlg.FilterIndex
=
0
;
dlg.RestoreDirectory
=
true
;
dlg.CreatePrompt
=
false
;
dlg.Title
=
"
保存为Excel文件
"
;
dlg.FileName
=
DateTime.Now.Ticks.ToString().Trim();
if
(dlg.ShowDialog()
==
DialogResult.OK)
{
Stream myStream;
myStream
=
dlg.OpenFile();
StreamWriter sw
=
new
StreamWriter(myStream, System.Text.Encoding.GetEncoding(
-
0
));
string
columnTitle
=
""
;
try
{
//
写入列标题
for
(
int
i
=
0
; i
<
dgv.ColumnCount; i
++
)
{
if
(i
>
0
)
{
columnTitle
+=
"
\t
"
;
}
columnTitle
+=
dgv.Columns[i].HeaderText;
}
sw.WriteLine(columnTitle);
//
写入列内容
for
(
int
j
=
0
; j
<
dgv.Rows.Count; j
++
)
{
string
columnValue
=
""
;
for
(
int
k
=
0
; k
<
dgv.Columns.Count; k
++
)
{
if
(k
>
0
)
{
columnValue
+=
"
\t
"
;
}
if
(dgv.Rows[j].Cells[k].Value
==
null
)
columnValue
+=
""
;
else
columnValue
+=
dgv.Rows[j].Cells[k].Value.ToString().Trim();
}
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
}
catch
(Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
}
}
}
4.冻结/恢复首列
//
冻结/恢复首列
void
clumnsFist_Click(
object
sender, EventArgs e)
{
if
(
this
.Columns.Count
>=
1
)
{
for
(
int
i
=
0
; i
<
this
.Columns.Count; i
++
)
{
if
(
this
.Columns[i].Visible
==
true
)
{
if
(
this
.Columns[i].Frozen)
{
this
.Columns[i].Frozen
=
false
;
((ToolStripMenuItem)sender).Text
=
"
冻结首列
"
;
return
;
}
else
{
this
.Columns[i].Frozen
=
true
;
((ToolStripMenuItem)sender).Text
=
"
恢复首列
"
;
return
;
}
}
}
}
}
5.冻结/恢复首行
//
冻结/恢复首行
void
rowsFistFist_Click(
object
sender, EventArgs e)
{
if
(
this
.Rows.Count
>=
1
)
{
if
(
this
.Rows[
0
].Frozen)
{
this
.Rows[
0
].Frozen
=
false
;
((ToolStripMenuItem)sender).Text
=
"
冻结首行
"
;
}
else
{
this
.Rows[
0
].Frozen
=
true
;
((ToolStripMenuItem)sender).Text
=
"
解冻首行
"
;
}
}
}
还有一个提供创建新的菜单项的方法
///
<summary>
///
创建新的菜单项
///
</summary>
///
<param name="name">
菜单名
</param>
///
<param name="Text">
显示文字
</param>
///
<param name="objEh">
绑定事件
</param>
///
<returns>
返一个ToolStripMenuItem对象
</returns>
private
ToolStripMenuItem createItem(
string
name,
string
Text, EventHandler objEh)
{
System.Windows.Forms.ToolStripMenuItem lolumns
=
new
System.Windows.Forms.ToolStripMenuItem();
lolumns.ForeColor
=
System.Drawing.Color.Black;
lolumns.Name
=
name;
lolumns.Size
=
new
System.Drawing.Size(
152
,
24
);
lolumns.Text
=
Text;
lolumns.Click
+=
objEh;
return
lolumns;
}
我把全部代码放上大家多多指教
View Code
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Diagnostics;
using
System.Text;
using
System.Drawing;
using
System.Windows.Forms;
using
bxyztSkin.csList;
namespace
bxyztSkin.Editors
{
public
partial
class
CDataGridView : System.Windows.Forms.DataGridView
{
///
<summary>
///
类说明:CDataGridView控件的实现用来代替系统的DataGridView控件
///
编码日期:2011-03-02
///
编 码 人: 苏飞
///
联系方式:361983679 Email:[email protected] Blogs:
http://sufei.cnblogs.com
///
</summary>
public
CDataGridView()
{
this
.SetStyle(ControlStyles.DoubleBuffer
|
ControlStyles.AllPaintingInWmPaint,
true
);
}
//
[Description("是否调用复制的开关,True为开启,False为不开启"), EditorBrowsable(EditorBrowsableState.Always), Browsable(true)]
//
public Boolean clipboard { get; set; }
//
[Description("复制的单元格号码从0开始"), EditorBrowsable(EditorBrowsableState.Always), Browsable(true)]
//
public int clipboardnumber { get; set; }
//
[Description("行号的颜色"), EditorBrowsable(EditorBrowsableState.Always), Browsable(true)]
//
public Color RowIndexColor { get; set; }
protected
override
void
OnCreateControl()
{
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;
this
.AllowUserToOrderColumns
=
true
;
this
.AutoGenerateColumns
=
true
;
//
奇数行的颜色
this
.AlternatingRowsDefaultCellStyle.BackColor
=
Color.FromArgb(
216
,
229
,
248
);
base
.OnCreateControl();
#region
菜单体
bxyztSkin.CControls.CContextMenuStrip cmsleft
=
new
bxyztSkin.CControls.CContextMenuStrip();
cmsleft.Font
=
new
System.Drawing.Font(
"
微软雅黑
"
, 10F);
cmsleft.Name
=
"
cmsleft
"
;
cmsleft.Size
=
new
System.Drawing.Size(
61
,
4
);
#endregion
#region
注册菜单项
//
在这里添加菜单项
cmsleft.Items.Add(createItem(
"
clumnsFist
"
,
"
冻结首列
"
,
new
EventHandler(clumnsFist_Click)));
cmsleft.Items.Add(createItem(
"
rowsFist
"
,
"
冻结首行
"
,
new
EventHandler(rowsFistFist_Click)));
cmsleft.Items.Add(createItem(
"
officeExeceout
"
,
"
导出到Excel
"
,
new
EventHandler(officeExeceout_Click)));
cmsleft.Items.Add(createItem(
"
fullSelect
"
,
"
全选
"
,
new
EventHandler(fullSelect_Click)));
#endregion
#region
绑定菜单
Button objpb
=
new
Button();
objpb.BackgroundImage
=
bxyztSkin.Properties.Resources.caidan;
objpb.Location
=
new
Point(objpb.Location.X
+
9
, objpb.Location.Y
+
4
);
objpb.Width
=
17
;
objpb.Text
=
""
;
//
绑定一个右键菜单
objpb.ContextMenuStrip
=
cmsleft;
objpb.Cursor
=
System.Windows.Forms.Cursors.Hand;
objpb.Height
=
17
;
objpb.BackgroundImageLayout
=
ImageLayout.Stretch;
objpb.FlatStyle
=
FlatStyle.Popup;
//
在添加前先注册一个事件
objpb.Click
+=
new
EventHandler(objpb_Click);
this
.Controls.Add(objpb);
#endregion
}
#region
菜单项的事件集合
//
全选
void
fullSelect_Click(
object
sender, EventArgs e)
{
this
.SelectAll();
}
//
导出到Excel
void
officeExeceout_Click(
object
sender, EventArgs e)
{
if
(
this
.Rows.Count
>
0
)
{
OfficeManagerMentServices.DataGridViewToExcel(
this
);
}
}
//
冻结/恢复首列
void
clumnsFist_Click(
object
sender, EventArgs e)
{
if
(
this
.Columns.Count
>=
1
)
{
for
(
int
i
=
0
; i
<
this
.Columns.Count; i
++
)
{
if
(
this
.Columns[i].Visible
==
true
)
{
if
(
this
.Columns[i].Frozen)
{
this
.Columns[i].Frozen
=
false
;
((ToolStripMenuItem)sender).Text
=
"
冻结首列
"
;
return
;
}
else
{
this
.Columns[i].Frozen
=
true
;
((ToolStripMenuItem)sender).Text
=
"
恢复首列
"
;
return
;
}
}
}
}
}
//
冻结/恢复首行
void
rowsFistFist_Click(
object
sender, EventArgs e)
{
if
(
this
.Rows.Count
>=
1
)
{
if
(
this
.Rows[
0
].Frozen)
{
this
.Rows[
0
].Frozen
=
false
;
((ToolStripMenuItem)sender).Text
=
"
冻结首行
"
;
}
else
{
this
.Rows[
0
].Frozen
=
true
;
((ToolStripMenuItem)sender).Text
=
"
解冻首行
"
;
}
}
}
#endregion
///
<summary>
///
创建新的菜单项
///
</summary>
///
<param name="name">
菜单名
</param>
///
<param name="Text">
显示文字
</param>
///
<param name="objEh">
绑定事件
</param>
///
<returns>
返一个ToolStripMenuItem对象
</returns>
private
ToolStripMenuItem createItem(
string
name,
string
Text, EventHandler objEh)
{
System.Windows.Forms.ToolStripMenuItem lolumns
=
new
System.Windows.Forms.ToolStripMenuItem();
lolumns.ForeColor
=
System.Drawing.Color.Black;
lolumns.Name
=
name;
lolumns.Size
=
new
System.Drawing.Size(
152
,
24
);
lolumns.Text
=
Text;
lolumns.Click
+=
objEh;
return
lolumns;
}
//
Button单击事件
void
objpb_Click(
object
sender, EventArgs e)
{
Button objbootn
=
(Button)sender;
//
显示菜单的位置
objbootn.ContextMenuStrip.Show(Control.MousePosition.X, Control.MousePosition.Y);
}
#region
鼠标颜色
Color defaultcolor;
//
移到单元格时的颜色
protected
override
void
OnCellMouseMove(DataGridViewCellMouseEventArgs e)
{
base
.OnCellMouseMove(e);
try
{
Rows[e.RowIndex].DefaultCellStyle.BackColor
=
Color.YellowGreen;
}
catch
{ }
}
//
进入单元格时保存当前的颜色
protected
override
void
OnCellMouseEnter(DataGridViewCellEventArgs e)
{
base
.OnCellMouseEnter(e);
try
{
defaultcolor
=
Rows[e.RowIndex].DefaultCellStyle.BackColor;
}
catch
{ }
}
//
离开时还原颜色
protected
override
void
OnCellMouseLeave(DataGridViewCellEventArgs e)
{
base
.OnCellMouseLeave(e);
try
{
Rows[e.RowIndex].DefaultCellStyle.BackColor
=
defaultcolor;
}
catch
{ }
}
//
在生成列表时添加一个行号,颜色默认为红色
protected
override
void
OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
{
base
.OnRowPostPaint(e);
//
自动编号与数据库无关
Rectangle rectangle
=
new
Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, RowHeadersWidth
-
4
, e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex
+
1
).ToString(), RowHeadersDefaultCellStyle.Font, rectangle,
Color.Red, TextFormatFlags.VerticalCenter
|
TextFormatFlags.HorizontalCenter);
}
#endregion
}
}