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);
    
  • 相关阅读:
    OS__信号量(semaphore)PV操作
    c++ _宏与内联函数
    ubuntu_ root change to user
    联想Y450在Ubuntu下调节屏幕亮度
    AI—家庭组机器人平台环境配置,高级人工智能实验总结
    如何在ubuntu下使用windows下的程序(eg: .exe)
    Python_XML的三种解析方法
    Python学习资源汇总
    转:Emmet 学习之路
    sql入门
  • 原文地址:https://www.cnblogs.com/SunSpring/p/15407629.html
Copyright © 2011-2022 走看看