DataGridView添加右键菜单等技巧

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DataGridView添加右键菜单等技巧相关的知识,希望对你有一定的参考价值。


1). 添加一个快捷菜单contextMenuStrip1;
2). 给dataGridView1的CellMouseDown事件添加处理程序:

 程序代码
private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        if (e.RowIndex >= 0)
        {
            //若行已是选中状态就不再进行设置
            if (dataGridView1.Rows[e.RowIndex].Selected == false)
            {
                dataGridView1.ClearSelection();
                dataGridView1.Rows[e.RowIndex].Selected = true;
            }
            //只选中一行时设置活动单元格
            if (dataGridView1.SelectedRows.Count == 1)
            {
                dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            }
            //弹出操作菜单
            contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
        }
    }
}


效果图:

技术分享

2).复制选中单元格的内容到剪贴板

 程序代码
Clipboard.SetDataObject(dataGridView1.GetClipboardContent());


3).只显示自定义列

 程序代码
dataGridView1.AutoGenerateColumns = false;//必须在代码中设置


4).显示图片

通常,我们将图片路径保存在数据库中,但在dataGridView1中要显示图片,可以进行如下操作:

①.添加一个DataGridViewTextBoxColumn类型的列,Name=Path,DataPropertyName=Pic,Visible=False;
②.添加一个DataGridViewImageColumn类型的列,Name=Pic;
③.dataGridView1控件DataBindingComplete事件处理程序如下:

 程序代码
private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    Image image1 = null;
    Image image2 = null;
    string path = string.Empty;

    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        path = @"F:\\" + dataGridView1.Rows[i].Cells["Path"].Value;

        if (File.Exists(path))
        {
            image1 = Image.FromFile(path);
            image2 = new Bitmap(image1, 120, 120);//重设大小

            dataGridView1.Rows[i].Cells["Pic"].Value = image2;
            //((DataGridViewImageCell)dataGridView1.Rows[i].Cells["Pic"]).Value = image2;
        }
    }
}


5).当网格未填充满控件时,画线来填充空白区域

 程序代码
/// <summary>
/// 绘制网格填充空白区域
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    DataGridView myDataGridView = (DataGridView)sender;

    if (myDataGridView.Rows.Count > 0)
    {
        int i = myDataGridView.ColumnHeadersHeight;//标题行高
        int j = myDataGridView.Rows.GetRowsHeight(DataGridViewElementStates.Visible); //所有可见行总高
        int k = myDataGridView.Height; //控件高度
        int l = myDataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible);//最后一行索引
        int count = myDataGridView.Columns.Count;//列总数
        int width = 0;

        //当网格未充满控件时才画线
        if (i + j < k)
        {
            using (Brush gridBrush = new SolidBrush(myDataGridView.GridColor))
            {
                using (Pen gridLinePen = new Pen(gridBrush))
                {
                    //处理标题列
                    if (myDataGridView.RowHeadersVisible)
                    {
                        width = myDataGridView.RowHeadersWidth;
                        e.Graphics.DrawLine(gridLinePen, width, i + j, width, k);
                    }
                    else
                    {
                        width = 1;
                    }

                    //处理正常列
                    for (int index = 0; index < count; index++)
                    {
                        if (myDataGridView.Columns[index].Visible)
                        {
                            width += myDataGridView.Columns[index].Width;

                            e.Graphics.DrawLine(gridLinePen, width, i + j, width, k);
                        }
                    }
                }
            }
        }
    }
}


6).自定义列宽

手动添加列,再在编辑列界面中逐个设置宽度。注意AutoSizeColumnsMode的值必须为DataGridViewAutoSizeColumnsMode.None,否则自定义宽度不能生效!

7).单元格内容格式化

 程序代码
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridView myDataGridView = (DataGridView)sender;
    if (myDataGridView.Columns["ID"].Index == e.ColumnIndex)
    {
        if(e.Value != null && !string.IsNullOrEmpty(e.Value.ToString()))
            e.Value = "BH" + string.Format("{0:D8}", int.Parse(e.Value.ToString()));
    }
}


8).打造一个漂亮的DataGridView

 程序代码
//样式
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;//列宽不自动调整,手工添加列
dataGridView1.RowHeadersWidth = 12;//行标题宽度固定12
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;//不能用鼠标调整列标头宽度
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LemonChiffon;//奇数行背景色
dataGridView1.BackgroundColor = Color.White;//控件背景色
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列标题居中显示
dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//单元格内容居中显示

//行为
dataGridView1.AutoGenerateColumns = false;//不自动创建列
dataGridView1.AllowUserToAddRows = false;//不启用添加
dataGridView1.ReadOnly = true;//不启用编辑
dataGridView1.AllowUserToDeleteRows = false;//不启用删除
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//单击单元格选中整行
dataGridView1.MultiSelect = false;//不能多选


9).判断有无滚动条

 程序代码
//垂直滚动条
if (dataGridView1.Rows.GetRowsHeight(DataGridViewElementStates.None) > dataGridView1.Height)
    MessageBox.Show("有");
else
    MessageBox.Show("无");

//水平滚动条
if(dataGridView1.Columns.GetColumnsWidth(DataGridViewElementStates.None) > dataGridView1.Width)
    MessageBox.Show("有");
else
    MessageBox.Show("无");


10).为什么列标题总不居中?

已经将列标题默认对齐方式设置为居中:

 程序代码
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列标题居中显示


但实际的效果总是偏左了一点,原因是列可以进行排序,排序标志符号在列标题上占了空间。逐列按下边设置可去掉:

 程序代码
dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;


































































































































































以上是关于DataGridView添加右键菜单等技巧的主要内容,如果未能解决你的问题,请参考以下文章

如何在DataGridView上添加“右键菜单”

DataGridview加上右键菜单 .net 2005 c#

怎样禁止dataGridview更新,允许插入

右键单击 datagridview 的上下文菜单

C# winform datagridview中如何实现鼠标右键点击一行数据出现一个带有删除的菜单,并能执行删除操作?

winform如何从DataGridView中从右键菜单获取一行数据