C#开发WinForm之DataGridView用法
程序员文章站
2022-03-21 18:46:55
向datagridview添加n行。for(int i=0;i
- 向dataGridView添加n行。
for(int i=0;i<n;i++) { i = dataGridView_detail.Rows.Add(); dataGridView_detail.Rows[i].Cells[0].Value = i+1; dataGridView_detail.Rows[i].Cells[1].Value = value[i]; }
- 设置选中dataGridView的第i行并滚动到该行。
dataGridView_detail.Rows[i].Selected=true; dataGridView_detail.FirstDisplayedScrollingRowIndex = i;
- 初始的dataGridView最下边一行没有横线,强迫症看着难受。修改其ColumnHeadersBorderStyle属性为Raised。(PS:找了好久)
- dataGridView常用事件:
(1)使用其CellMouseClick实现鼠标右键选中dataGridView某项,弹出右键菜单(contextMenuStrip_items)。
private void dataGridView_detail_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (dataGridView_detail.Rows.Count == 0)
return;
if (dataGridView_detail.SelectedRows.Count == 0)//无选中信息
return;
if (e.Button == MouseButtons.Right)
{
Rectangle R = dataGridView_detail.GetRowDisplayRectangle(dataGridView_detail.CurrentCell.RowIndex,false);
System.Drawing.Point pos = new System.Drawing.Point(e.X, e.Y);
this.ToolStripMenuItem_delete.Visible = true;
this.contextMenuStrip_items.Show(MousePosition.X,MousePosition.Y);
}
}
catch(Exception ex)
{
ErrorLog.Error(ex.Message);
}
}
5. 在dataGridView数据较多时,拉动右边滚动条数据显示会很卡,可加速刷新速度。
public static class ExtensionMethods
{
public static void DoubleBuffered(this DataGridView dgv, bool setting)
{
Type dgvType = dgv.GetType();
PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
BindingFlags.Instance | BindingFlags.NonPublic);
pi.SetValue(dgv, setting, null);
}
}
//使用时引用命名控件
//dataGridView1.DoubleBuffered(true);
未完待续......
本文地址:https://blog.csdn.net/qq_41672428/article/details/107471259