`
wsql
  • 浏览: 11778613 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

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


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics