DataGridView使用

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

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

// 调整字体
dataGridView1.Font = new Font("宋体", 11);
// 调整行高
//dataGridView1.Rows[0].Height = 100;
dataGridView1.RowTemplate.Height = 30;
dataGridView1.Update();
// 调整列宽
dataGridView1.Columns[0].Width = 70;
dataGridView1.Columns[1].Width = 360;
dataGridView1.Columns[2].Width = 100;
dataGridView1.Columns[3].Width = 239;

至于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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值