WindForm DataGridView 表格基础

DataGridView常见操作

1、复制选中单元格的内容到剪贴板

Clipboard.SetDataObject(dataGridView1.GetClipboardContent());

2、只显示自定义列

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

3、显示图片

通常,我们将图片路径保存在数据库中,但在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;
    	}
}
4、当网格未填充满控件时,画线来填充空白区域
  /// 
  /// 绘制网格填充空白区域  /// 
  /// 
  /// 
  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);
                          }
                      }
                  }
              }
          }
   }
5、自定义列宽

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

6、单元格内容格式化
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()));
      }
  }
7、打造一个漂亮的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;//不能多选
8、判断有无滚动条
	//垂直滚动条
	  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("无");

9、为什么列标题总不居中?

已经将列标题默认对齐方式设置为居中:
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列标题居中显示
但实际的效果总是偏左了一点,原因是列可以进行排序,排序标志符号在列标题上占了空间。逐列按下边设置可去掉:
dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;

DataGridView 增加右键菜单

1).右键点击行时选中行,并弹出操作菜单

2). 添加一个快捷菜单contextMenuStrip1;

3). 给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);
          }
      }
  }
效果图

image

DataGridView Remove无法删除未提交的新行

C#dataGridView Remove()不会清除dataGridView行,想要清除dataGridView?循环移除行是不行的:

foreach (DataGridViewRow row in dataGridView.Rows)
 {
     dataGridView.Rows.Remove(row);
 }

for (int i = 0; i < dataGridView.Rows.Count; i++)
 {
     dataGridView.Rows.RemoveAt(i);
 }

已有项的dataGridView不会删除这些项,执行到最后项仍存在,即使dataGridView的Row Count数的确在减小。这算是Bug吧?
完全清除需要这么做:

dataGridView.Rows.Clear();

DataGridView 增加全选列

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;
namespace CheckBoxDemo
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
        InitDtSource();
    }

    private void cbHeader_OnCheckBoxClicked(bool state)
    {
        //这一句很重要结束编辑状态
        dgInfo.EndEdit();
        dgInfo.Rows.OfType<DataGridViewRow>().ToList().ForEach(t => t.Cells[0].Value = state);
    }
	//测试使用
    private void InitDtSource()
    {
        try
        {
            var _dtSource = new DataTable();
            //1、添加列
            _dtSource.Columns.Add("姓名", typeof(string)); //数据类型为 文本
            _dtSource.Columns.Add("身份证号", typeof(string)); //数据类型为 文本
            _dtSource.Columns.Add("时间", typeof(string)); //数据类型为 文本
            _dtSource.Columns.Add("地点", typeof(string)); //数据类型为 文本
           for (int i = 0; i < 10; i++)
           {
               DataRow drData = _dtSource.NewRow();
               drData[0] = "test" + i;
               drData[1] = "35412549554521263" + i;
               drData[2] = "2017-05-21 10:55:21";
               drData[3] = "北京市";
               _dtSource.Rows.Add(drData);
           }
        dgInfo.DataSource = _dtSource;
        InitColumnInfo();
      }
       catch (Exception ex) {}
    }
    //添加全选列
    private void InitColumnInfo()
    {
        int index = 0;
        DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();
        DatagridViewCheckBoxHeaderCell cbHeader = new DatagridViewCheckBoxHeaderCell();
        colCB.HeaderCell = cbHeader;
        colCB.HeaderText = "全选";
        cbHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);
        dgInfo.Columns.Insert(index, colCB);


        index++;
        dgInfo.Columns[index].HeaderText = "姓名";
        dgInfo.Columns[index].Width = 90;

        index++;
        dgInfo.Columns[index].HeaderText = "身份证号";
        dgInfo.Columns[index].Width = 120;

        index++;
        dgInfo.Columns[index].HeaderText = "时间";
        dgInfo.Columns[index].Width = 150;

        index++;
        dgInfo.Columns[index].HeaderText = "地点";
        dgInfo.Columns[index].Width = 100;

        System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
        dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223, 240
        dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Blue;
        dataGridViewCellStyle2.SelectionForeColor = System.Drawing.Color.Blue;
        dgInfo.Columns[index].DefaultCellStyle = dataGridViewCellStyle2;
    }
}


public delegate void CheckBoxClickedHandler(bool state);
public class DataGridViewCheckBoxHeaderCellEventArgs : EventArgs
{
    bool _bChecked;
    public DataGridViewCheckBoxHeaderCellEventArgs(bool bChecked)
    {
        _bChecked = bChecked;
    }
    public bool Checked
    {
        get { return _bChecked; }
    }
}

class DatagridViewCheckBoxHeaderCell : DataGridViewColumnHeaderCell
{
    Point checkBoxLocation;
    Size checkBoxSize;
    bool _checked = false;
    Point _cellLocation = new Point();
    System.Windows.Forms.VisualStyles.CheckBoxState _cbState = System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal;

    public event CheckBoxClickedHandler OnCheckBoxClicked;

    public DatagridViewCheckBoxHeaderCell()
    {
    }

    protected override void Paint(System.Drawing.Graphics graphics,
        System.Drawing.Rectangle clipBounds,
        System.Drawing.Rectangle cellBounds,
        int rowIndex,
        DataGridViewElementStates dataGridViewElementState,
        object value,
        object formattedValue,
        string errorText,
        DataGridViewCellStyle cellStyle,
        DataGridViewAdvancedBorderStyle advancedBorderStyle,
        DataGridViewPaintParts paintParts)
    {
        base.Paint(graphics, clipBounds, cellBounds, rowIndex,
            dataGridViewElementState, value,
            formattedValue, errorText, cellStyle,
            advancedBorderStyle, paintParts);
        Point p = new Point();
        Size s = CheckBoxRenderer.GetGlyphSize(graphics,
        System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
        p.X = cellBounds.Location.X +
            (cellBounds.Width / 2) - (s.Width / 2);
        p.Y = cellBounds.Location.Y +
            (cellBounds.Height / 2) - (s.Height / 2);
        _cellLocation = cellBounds.Location;
        checkBoxLocation = p;
        checkBoxSize = s;
        if (_checked)
            _cbState = System.Windows.Forms.VisualStyles.
                CheckBoxState.CheckedNormal;
        else
            _cbState = System.Windows.Forms.VisualStyles.
                CheckBoxState.UncheckedNormal;
        CheckBoxRenderer.DrawCheckBox
        (graphics, checkBoxLocation, _cbState);
    }

    protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
    {
        Point p = new Point(e.X + _cellLocation.X, e.Y + _cellLocation.Y);
        if (p.X >= checkBoxLocation.X && p.X <=
            checkBoxLocation.X + checkBoxSize.Width
        && p.Y >= checkBoxLocation.Y && p.Y <=
            checkBoxLocation.Y + checkBoxSize.Height)
        {
            _checked = !_checked;
            if (OnCheckBoxClicked != null)
            {
                OnCheckBoxClicked(_checked);
                this.DataGridView.InvalidateCell(this);
            }

        }
        base.OnMouseClick(e);
    }
}
} 
posted @ 2022-08-31 17:44  Topi  阅读(139)  评论(0)    收藏  举报