Winform学习笔记(六)——DataGridView的使用

本文详细介绍了Winform应用中DataGridView的使用,包括常用属性如AllowUserToAddRows和ReadOnly,如何添加序号,处理CellContentClick事件,添加按钮和CheckBox,以及选中行的上移、下移、删除操作,以及遍历数据显示和CheckBox状态的方法。

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

1.常用属性

允许添加一行(空白行): AllowUserToAddRows:True / False
调整列宽属性:AutoSizeColumnsMode
是否只读:ReadOnly:True / False
选中整行数据:SelectionMode:RowHeaderSelect

2.DataGridView添加序号

在datagridview的RowPostPaint事件中加入此方法

private void dataGridView1_RowPostPaint(object sender,  DataGridViewRowPostPaintEventArgs e)
{
   
    SolidBrush b = new  SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
    e.Graphics.DrawString((e.RowIndex +  1).ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20,  e.RowBounds.Location.Y + 4);
}

3.事件

控件点击事件(CellContentClick),获取点击行数据

private void dataGridView1_CellContentClick(object sender,  DataGridViewCellEventArgs e)
{
   
    if (e.RowIndex >= 0)
    {
   
        DataTable dt = (DataTable)dataGridView1.DataSource;
        string id= dt.Rows[e.RowIndex]["id"].ToString();
        string name = dt.Rows[e.RowIndex]["name"].ToString();
        if  (dataGridView1.Columns[e.ColumnIndex].Name.Equals("id"))
        {
   
             MessageBox.Show(dataGridView1.Columns[e.ColumnIndex].ToString());
        }
    }
}

4.DataGridView中添加按钮以及按钮点击事件

//添加按钮
DataGridViewButtonColumn DGBC1 = new DataGridViewButtonColumn();
DGBC1.HeaderText = "操作";
DGBC1.Name = "updateUser";
DGBC1.DefaultCellStyle.NullValue = "修改角色";
dataGridView1.Columns.Add(DGBC1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值