C#中关于DataGridView行和列的背景色-前景色设置
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C#中关于DataGridView⾏和列的背景⾊-前景⾊设置
关于DataGridView⾏和列的背景⾊-前景⾊设置
1.设定DataGridView全部单元格的Style
DataGridView内所有单元格的Style变更,可以使⽤DataGridView对象的DefaultCellStyle属性实现。
//包含Header所有的单元格的背景⾊为黄⾊
DataGridView1.DefaultCellStyle.BackColor = Color.Yellow;
//包含Header所有的单元格的前景⾊为黄⾊
DataGridView1.DefaultCellStyle.ForeColor= Color.Yellow; //前景⾊设置,只需要将BackColor改为ForeColor即可
2.DataGridView.DefaultCellStyle属性可以对包含Header所有单元格的Style进⾏变更设定,对除 Header以外所有单元格的Style进⾏变更,可以使⽤DataGridView.RowsDefaultCellStyle属性实现
// Header以外所有的单元格的背景⾊为黄⾊
DataGridView1.RowsDefaultCellStyle.BackColor = Color.Yellow;
3.变更某⼀个单元格的Style
DataGridViewCell.Style属性可以对单⼀的单元格的Style进⾏变更设定。
如下⾯的例⼦,只对(0, 0)单元格的背景⾊设定为粉红⾊。
//(0, 0)单元格的背景⾊为粉⾊
DataGridView1[0, 0].Style.BackColor = Color.Pink;
4.变更被指定的列、⾏的单元格的Style
DataGridViewColumn.DefaultCellStyle属性,可以对列的单元格Style进⾏变更设定。
DataGridViewRow.DefaultCellStyle属性,可以对⾏的单元格Style进⾏变更设定。
如下⾯的例⼦,第⼀列的单元格的背景⾊为淡蓝⾊,第⼀⾏的单元格的背景⾊为淡灰⾊。
//索引0列的单元格的背景⾊为淡蓝⾊
DataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Aqua;
//索引0⾏的单元格的背景⾊为淡灰⾊
DataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.LightGray;
5.变更奇数⾏的单元格Style
DataGridView.AlternatingRowsDefaultCellStyle属性,可以变更DataGridView的奇数⾏的单元格 Style。
如下⾯的例⼦,奇数⾏的单元格的背景⾊设定为黄绿⾊
//奇数⾏的单元格的背景⾊为黄绿⾊
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow;
6.变更列Header、⾏Header的单元格Style
列Header的单元格style的变更,可以使⽤,DataGridView.ColumnHeadersDefaultCellStyle属性实现。
⾏ Header的单元格Style的变更,可以使⽤DataGridView.RowHeadersDefaultCellStyle属性实现。
但是,Header 的是左侧的单元格需要通过
DataGridView.TopLeftHeaderCell属性,取得的DataGridViewHeaderCell对象的单元格Style进⾏设定。
如下⾯的例⼦,列Header的背景⾊为象⽛⾊,⾏Header的背景⾊为橙⾊。
//列Header的背景⾊为象⽛⾊
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Ivory;
//⾏Header的背景⾊为橙⾊
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Lime;
补充:每个Header单元格的单元格Style,可以使⽤这⼀些的⽅法取得,和⼀般的单元格⼀样,可以使⽤Style 属性变更,简⽽⾔之,就是个可以对每个单元格进⾏个性化设置。
关于优先顺序
设定单元格Style的属性有优先顺序的。
顺序从⾼到低如下所⽰。
1). DataGridViewCell.Style
2). DataGridViewRow.DefaultCellStyle
3). DataGridView.AlternatingRowsDefaultCellStyle
4). DataGridView.RowsDefaultCellStyle
5). DataGridViewColumn.DefaultCellStyle
6). DataGridView.DefaultCellStyle
接下来是Header的单元格Style属性的优先顺序。
1). DataGridViewCell.Style
2). DataGridView.RowHeadersDefaultCellStyle
3). DataGridView.ColumnHeadersDefaultCellStyle
4). DataGridView.DefaultCellStyle
单元格本⾝的设定的Style是最优先的。