zoukankan      html  css  js  c++  java
  • WinForm 控件 DataGridView 常用操作

    1、取消列自动生成

    在窗体load事件里面设置表格dataGridView的AutoGenerateColumns为 false

    dataGridView.AutoGenerateColumns = false
    

    2、取消所有选中单元格

    调用方法ClearSelection

    dataGridView.ClearSelection()
    

    3、单元格自动换行显示

    设置DefaultCellStyle 里面的WarapMode 属性为 true

    image.png

    4、行显示高度自动调节

    设置属性 AutoSizeRowModeDisplayedCellsExceptHeaders 设置方法AutoResizeColumns

    dataGridView.AutoSizeRowsMode=DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
    dataGridView.AutoResizeColumns();
    

    5、首列添加序号

    表格RowPostPaint事件

     private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
     {
        //获取行对象
        var row = dataGridView.Rows[e.RowIndex];
        //对行的第一列value赋值
        row.Cells[0].Value = row.Index + 1;
     }
    

    6、行头绘制图片

    表格RowPostPaint事件绘制图片或者数字

     private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
     {
         //读取要显示的图片
         Image img = Properties.Resources.img
         //绘制图标,图标绘制的坐标位置可自己调节
         e.Graphics.DrawImage(img, e.RowBounds.Left + dataGridView.RowHeadersWidth - 40, e.RowBounds.Top + 4, 16, 16);
     }
    

    7、转换单元格显示

    在表格的CellFormatting事件里面进行转换操作,比如一个状态字段是int类型,显示需要转换成对应的字符串显示。

    private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        //转换第一列
        if (e.ColumnIndex == 0)
        {
            //取得行
            var row = dataGridView.Rows[e.RowIndex];
            //取得列值,如果是绑定的数据,可以将row.DataBoundItem转换成绑定对象再取值判断
            var cell=row.cell[0].value.ToString();
            string grad = "";
            if cell == "1")
                grad = "A";
            else if (cell == "2")
                grad = "B";
            else if (cell == "3")
                grad = "C";
            else if (cell == "4")
                grad = "D";
            else if (cell == "5")
                grad = "E";
            e.Value = grad;
        }
              
    }
    

    8、右键选中单元格

    在表格的CellMouseDown事件里面设置选中行

    private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
        {
            dataGridView.CurrentRow.Selected = false;
            dataGridView.Rows[e.RowIndex].Selected = true;
        }
    }
    

    9、修改单元格值,单行刷新重绘

    //dgvBook.SelectedRows[0].Index 为要刷新的行号
     dataGridView.InvalidateRow(dgvBook.SelectedRows[0].Index);
    
  • 相关阅读:
    MSCRM 2011 修改显示记录数
    医疗相关名词解析
    把图片中的文字转成文本
    自我介绍吧
    第三次作业
    第一次作业心得
    耿丹161第一次作业
    第二次作业
    C#常用函数表及Asp.net(C#)常用函数表
    C语言I博客作业02
  • 原文地址:https://www.cnblogs.com/SunSpring/p/15407629.html
Copyright © 2011-2022 走看看