Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The short answer is that this cannot be done without manually creating the columns (and setting the <code>DataPropertyName</code> property) before binding. There is no attribute you can use to decorate your data source, the <code>DataGridView</code> will simply generate a <code>DataGridViewTextBoxColumn</code> for every data type (except <code>Boolean</code> which it will resolve to a checkbox column). This behaviour is internal and unchangeable.</p> <p>Your best bet is to disable <code>AutoGenerateColumns</code> on the grid and write your own method that dynamically generates appropriate column types, perhaps based on your own custom attribute, such as (from your example above):</p> <pre><code>[DisplayName(@"Time"), ColumnType(typeof(DataGridViewButtonColumn))] public DateTime TimePosted { get; set; } </code></pre> <p>The attribute class is easy to write (just extend <code>Attribute</code>, add a <code>Type</code> field and an appropriate constructor). In the method that will generate the columns (immediately before binding), you can use reflection to crawl for properties and check for the presence of the custom attribute. (<code>BindingSource.GetItemProperties()</code> is very useful for obtaining information about the properties on objects in a collection.)</p> <p>This is not the most elegant solution (and it delves into some intermediate-level concepts), but it's the only way to get around this limitation with auto-generated columns in the <code>DataGridView</code> control.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload