C#DataGridView显示设置

本文详细介绍了如何使用C#代码对DataGridView控件进行个性化设置,包括列名居中、字体设置、列宽调整、列显示模式、行居中、字体加粗、选中颜色更改、单元格多行显示以及在每行添加递增序号等操作。

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

            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列名居中
            this.dataGridView1.RowsDefaultCellStyle.Font = new Font("宋体", 10);//设置列字体
            this.dataGridView1.Columns[1].Width = 80;//设置列宽
            this.dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;//设置列显示模式
            
            dataGridView1.ReadOnly = false;
            foreach(DataGridViewColumn c in dataGridView1.Columns)
            {
                if(c.Index!=2)
                {
                    c.ReadOnly = true;//禁止某列编辑
                }
                c.SortMode= DataGridViewColumnSortMode.NotSortable;//列不能排序
            }
            this.dataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//所有行居中
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("仿宋", 13, FontStyle.Bold);//设置字体

            this.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black;//改变默认选中的颜色
            this.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.White;


            this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;//允许单元格多行显示

 

        //在每行的左边为每行添加一个从1开始递增的序号
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush solidBrush = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture),
                this.dataGridView1.DefaultCellStyle.Font, solidBrush,
                e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 6);
            e.Graphics.FillRectangle(Brushes.White, new Rectangle(new Point(e.RowBounds.Location.X + 2, 
                e.RowBounds.Location.Y + 2), new Size(20, 20)));//隐藏每行前面的图标
        }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值