在使用DataGridView这个控件时经常需要遍历单元格进行取值或者更改值,其代码如下:
//使用for循环
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
//获取第i行,列名是列名A的单元格的值
string a = dataGridView.Rows[i].Cells["列名A"].Value.ToString();
}
//使用foreach
foreach(DataGridViewRow row in DataGridView.Rows){
//获取第i行,列名是列名A的单元格的值
string a = row.Cells["列名A"].Value.ToString();
}
在平时的编码时,对gridview进行处理还有其他方法,就是datagridview自带的方法CellFormatting和CellPainting方法,这两个方法会一直循环遍历整个datagridview.
1.CellFormatting方法,一般可用于数值转换、根据不同值对不同行进行渲染等
private void datagridview_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewRow row = datagridview.Rows[e.RowIndex];
if (row.Cells["列名"].Value.Equals("列名A"))
{
row.DefaultCellStyle.BackColor = Color.MistyRose;//浅玫瑰色
//还可以加其他操作
}
}
2.CellPainting方法,作用同上,注意两个方法中参数e均代表的是循环的单元格
private void datagridview_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if(e.RowIndex > -1 && e.ColumnIndex > -1)//必须加,这个循环是会加上表头,值为-1.
{
DataGridViewRow row1 = datagridview.Rows[e.RowIndex];//获取当前行
DataGridViewCell cell = row1.Cells[e.ColumnIndex];//获取当前单元格
if (cell.OwningColumn.Name.Equals("列名A"))
{
//自己加操作
}
}
}