在实践项目中,有时为了界面美观,需要将数据表进行美化,比如隔行显示不同颜色。
属性
获取或设置应用于 System.Windows.Forms.DataGridView 的行单元格的默认样式。
public DataGridViewCellStyle RowsDefaultCellStyle { get; set; }
获取或设置应用于 System.Windows.Forms.DataGridView 的奇数行的默认单元格样式。
public DataGridViewCellStyle AlternatingRowsDefaultCellStyle { get; set; }
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
-
- namespace Test2_DataGridView
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- //绑定数据源
- this.dataGridView1.DataSource = Source();
- //设置行背景色
- this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Red;
- this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Green;
- }
-
- //数据表资源
- private DataTable Source()
- {
- DataTable mydt = new DataTable();
- mydt.Columns.Add("姓名");
- mydt.Columns.Add("年龄");
- mydt.Columns.Add("分数");
- String[,] str = new String[,] { { "张三", "21", "90" }, { "李四", "22", "93" }, { "王五", "23", "99" }, { "赵六", "28", "80" }, { "孙七", "27", "86" } };
-
- for (int i = 0; i < 5; i++)
- {
- DataRow dr = mydt.NewRow();
- dr[0] = str[i, 0];
- dr[1] = str[i, 1];
- dr[2] = str[i, 2];
- mydt.Rows.Add(dr);
- }
- return mydt;
-
- }
- }
- }