Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've recently had a similar usecase, and ended up writing something like the below code:</p> <p>Write a custom Cell and Column class, and override the EditType and InitializeEditingControl methods on the cell, to return different controls as appropriate (here I'm just databinding to a list of a custom class with .useCombo field indicating what control to use):</p> <pre><code>// Define a column that will create an appropriate type of edit control as needed. public class OptionalDropdownColumn : DataGridViewColumn { public OptionalDropdownColumn() : base(new PropertyCell()) { } public override DataGridViewCell CellTemplate { get { return base.CellTemplate; } set { // Ensure that the cell used for the template is a PropertyCell. if (value != null &amp;&amp; !value.GetType().IsAssignableFrom(typeof(PropertyCell))) { throw new InvalidCastException("Must be a PropertyCell"); } base.CellTemplate = value; } } } // And the corresponding Cell type public class OptionalDropdownCell : DataGridViewTextBoxCell { public OptionalDropdownCell() : base() { } public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { // Set the value of the editing control to the current cell value. base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); DataItem dataItem = (DataItem) this.OwningRow.DataBoundItem; if (dataItem.useCombo) { DataGridViewComboBoxEditingControl ctl = (DataGridViewComboBoxEditingControl)DataGridView.EditingControl; ctl.DataSource = dataItem.allowedItems; ctl.DropDownStyle = ComboBoxStyle.DropDownList; } else { DataGridViewTextBoxEditingControl ctl = (DataGridViewTextBoxEditingControl)DataGridView.EditingControl; ctl.Text = this.Value.ToString(); } } public override Type EditType { get { DataItem dataItem = (DataItem)this.OwningRow.DataBoundItem; if (dataItem.useCombo) { return typeof(DataGridViewComboBoxEditingControl); } else { return typeof(DataGridViewTextBoxEditingControl); } } } } </code></pre> <p>Then just add a column to your DataGridView of this type, and the correct edit control should be used.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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