现在的位置: 首页 > 综合 > 正文

C#中DataGridView使用

2018年02月18日 ⁄ 综合 ⁄ 共 1746字 ⁄ 字号 评论关闭
文章目录

1. DataGridView设置字体、行高、列宽、单列居中

DataGridView表格内容列宽行高字体的设置,设置某一列居中。一般地,会将行高设为统一的,列宽根据不同情况设定。

// 调整字体
dataGridView1.Font = new Font("宋体", 11);
// 调整行高
//dataGridView1.Rows[0].Height = 100;
dataGridView1.RowTemplate.Height = 30;
dataGridView1.Update();
// 调整列宽,注意autosizecolumnsmode属性不能设置为fill
dataGridView1.Columns[0].Width = 70;
dataGridView1.Columns[1].Width = 360;
dataGridView1.Columns[2].Width = 100;
dataGridView1.Columns[3].Width = 239;
// 设置某一列居中
dataGridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

至于DataGridView行头和列头(即表头部分)的设置可直接在控件的属性窗口中设置。相关的属性是ColumnHeader...和RowHeader...。

可能存在的问题:设置行高后若需要刷新两次后才显示为新设置的行高,则可以通过把设置行高部分的代码拷贝到构造函数中解决。

2. DataGridView单击选中整行

方法一

//设置为整行被选中
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

上述代码加到构造函数中即可,其他能被调用的地方也可。

方法二:添加事件(但是不完美)

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = true;
    Console.WriteLine("点击内容...");
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = true;
    Console.WriteLine("点击Cell...");
}

这种方法存在两个问题:一是,采用CellContentClick事件时,当单击单元格空白处时,不会选中整行,仍是选中单元格,单击单元格中文字时,可以选中整行;二是,不支持选中多行,即选多行时,仍是选中多个单元格。

注意:要使事件监听生效,需要在XXX.designer.cs文件中InitializeComponent方法中添加注册事件相关的代码

this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);

3 DataGridView属性

AllowUserToDeleteRows:是否允许用户使用“delete”键删除选中行。true:允许;false:不允许。

4 DataGridView相关

刷新DataGridView时,会出现每次刷新都在最后自动添加一行的问题。如下解决:

this.dataGridView1.Rows.Clear();

抱歉!评论已关闭.