dataGridView RowDataBound event





When working on a simple winForms application the other night, I wanted to manipulate some of the data being rendered on a row by row baisis. I soon found out that there is no equivalent RowDataBound event to the ASP.NET GridView event  in the winForms dataGridView control. Google-ing this i found a workaround in using the DataGridView.CellFormatting event.

However this still wasn’t perfect as I wanted to process row by row, not cell by cell.

A simple work around solution was to build the row information in the CellFormatting event and use the final column index to reset my row.

My example below assumes my grid has 3 columns, date,description and value.

First create a MyRow Class:
class MyRow
{
public DateTime Date { get; set; }
public string Description { get; set; }
public double Value { get; set; }

public MyRow()
{
}
}

Next my Form code:

public partial class Form1 : Form
{
private MyRow myRow;
const int MaxColumnsInGrid = 3;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
myRow = new MyRow();
}

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
switch (e.ColumnIndex)
{
case 0: myRow.Date = Convert.ToDateTime(e.Value); break;
case 1: myRow.Description = e.Value.ToString(); break;
case 2:
{
myRow.Value = Convert.ToDouble(e.Value);

//At this point myRow Object is complete
//and we can call a function that manipulates it as a whole

//Apply Vat Rate to the Value Column
dataGridView1.Rows[e.RowIndex].Cells[e.RowIndex].Value = ApplyVatToValue(myRow);

break;
}
}

}

private double ApplyVatToValue(MyRow myRow)
{
if(myRow.Date>= new DateTime(2011,1,4))
{
return myRow.Value * 1.20;
}
else
{
return myRow.Value * 1.175;
}
}
}

This is a simple example, but the techique can be used to process larger datagrids on a row by row basis, effectively simulating a DataRowBound event.

happy coding,
Robert Bertora.




Tags: , , , , ,

2 Responses to “dataGridView RowDataBound event”

  1. JJ says:

    Nice post.
    Just a quick thing about the line
    dataGridView1.Rows[e.RowIndex].Cells[e.RowIndex].Value
    Should not it be
    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value
    instead?

  2. Robert Bertora says:

    yes well spotted!