C# – Programmatically add new column to DataGridView

cdatagridviewwinforms

I have a DataGridView bound to a DataTable. The DataTable is populated from a database query. The table contains a column named BestBefore. BestBefore is a date formatted as a string (SQLite doesn't have date types).

I would like to programmatically add a new column to the DataGridView called Status. If BestBefore is less than the current date, Status value should be set to OK, otherwise Status value should be set to NOT OK.

I'm very new to Winforms, so some example code would be greatly appreciated.

UPDATE:

I think DataColumn.Expression is okay for doing simple calculations such multiplying a column's integer value by another value, but what about doing what I need to do? That is, calculate the difference between now and the date (string formatted) in the BestBefore column to determine what value to give the new status column. Example code would be appreciated.

Best Answer

Keep it simple

dataGridView1.Columns.Add("newColumnName", "Column Name in Text");

To add rows

dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]
Related Topic