C# DataGridView隔行变色&鼠标经过改变形状、固定行高、行号、列自动填充等等

本文介绍如何使用简单代码实现DataGridView的隔行变色效果,并提供鼠标悬停时改变行背景颜色及鼠标形状的方法。此外,还展示了如何禁止用户调整行高、设置列宽自动填充以及显示行号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设置数据列表控件隔行变色

只需两句代码即可搞定,非常舒服。

dataGridViewX1.RowsDefaultCellStyle.BackColor = Color.FromArgb(237, 243, 254);
dataGridViewX1.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(199, 237, 204);

 

鼠标经过改变形状及行变色

参照:http://www.cnblogs.com/greatverve/archive/2012/08/09/DataGridView-MouseEnter-MouseLeave.html

首先添加CellMouseEnter()与CellMouseLeave()事件。

/// <summary>
/// 用来记录先前的颜色值
/// </summary>
Color colorTmp = Color.White;
/// <summary>
/// 记录鼠标形状
/// </summary>
Cursor cursorTmp = Cursor.Current;
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        colorTmp = dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor;
        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Silver;
        if (e.ColumnIndex == 1)//改变第二列鼠标形状
        {
            cursorTmp = this.Cursor;
            this.Cursor = Cursors.Hand;
        }
    }
}

private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = colorTmp;
        if (e.ColumnIndex == 1)
        {
            this.Cursor = cursorTmp;
        }
    }
}

 禁止用户改变DataGridView1所有行的行高
DataGridView1.AllowUserToResizeRows = false;

列宽度自动填充:

 

AutoSizeColumnsMode属性设为Fill;
http://blog.youkuaiyun.com/lenovouser/article/details/6000169

 

行号显示:

http://blog.youkuaiyun.com/xieyufei/article/details/9769631

http://www.cnblogs.com/JuneZhang/archive/2011/11/21/2257630.html

http://www.jb51.net/article/40686.htm

private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();
 
    var centerFormat = new StringFormat() 
    { 
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center, 
        LineAlignment = StringAlignment.Center
    };
 
    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值