Populating a .NET DataGrid with data retrieved using a DataSet or a DataReader is very simple, but what if we need to display a computed column? That’s where the Expression feature of a DataColumn comes in ADO.NET. An Expression allows you to create virtual in-memory columns where content is obtained as the result of an expression applied to other existing columns.
In this example we’re going to retrieve data from SQL Server's pubs database, and create a column containing the authors advance divided by the price of the book. Not numerically significant, but it is a working example written in C#...
private void Page_Load(object sender, System.EventArgs e)
SqlConnection sqlConnection =
new SqlConnection("your connection string");
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM Titles",
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
DataColumn myColumn =
myColumn.Expression = "advance / price";
DataGrid1.DataSource = ds;
Of course the expression should check for division by zero, which isn't a problem with pub's title prices, but to be safe, the following would generate a null value instead of throwing an exception:
myColumn.Expression = "advance / IIF(price=0, NULL, price)";