1、数据绑定
下面将介绍用DataTable对DataGridView控件进行绑定。
首先得到DataTable dt,dt中的列为“id”,“pName”,“Short_Name”,......。
其次:设置DataGridView控件(dgvProductName)的列,如下图所示。注意:列的个数要与DataTable 相同,不想显示的列可以设置visible属性
第三将DataTable字段与DataGridView列绑定
this.dgvProductName.Columns["id"].DataPropertyName = dt.Columns["id"].ColumnName;
this.dgvProductName.Columns["pName"].DataPropertyName = dt.Columns["pName"].ColumnName;
......
第四将DataTable绑定到DataGridView
this.dgvProductName.DataSource = dt.
完成。
2、在行头上显示行号,并且各行换颜色
在RowPostPaint事件中写如下代码
3、绑定时,根据单元格数据的特性,将单元格变颜色。
譬如:某列数据大于100就设为红色。
在CellFormatting事件中写代码
private void dgvProductName_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (Convert.ToDouble(this.dgvProductName.Rows[e.RowIndex].Cells["Instock"].Value) <100.0
)
{
this.dgvProductName.Rows[e.RowIndex].Cells["Instock"].Style.ForeColor = Color.Red;
}
//整行变为红色
//e.CellStyle.ForeColor = Color.Red;
}
以上是自己的总结,希望对大家有所帮助。