You are getting the error because you have not defined any columns for the datagridview.
You could do this at design time by right-click on the control and choosing "Add column..." but this would tightly bind your UI to the current implementation of
facade.GetPurchase
so is not the best solution.
You could also add the columns programatically e.g.
dgv.Columns.Add(...
but again this is not recomemended because if your purchaseentity class changes you have to make changes elsewhere (breaks the principle of encapsulation for example).
You are not actually binding data to the control - with your
foreach
loop you are trying to create individual rows.
My advice would be to convert your
List<purchaseentity></purchaseentity>
to a
DataTable
and then use
dgv.DataSource = dt.DefaultView;
If you are not in a position to change
facade.GetPurchase
to return a DataTable instead of a List then you can convert the List using the following function
public DataTable ConvertToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}