How to show TextBox and Combobox alternatively in GridComboBoxColumn in WinForms DataGrid (SfDatGrid)?
This example illustrates how to show TextBox and Combobox alternatively in GridComboBoxColumn in WinForms DataGrid (SfDatGrid)?
WinForms DataGrid (SfDataGrid) doesn't have direct support to display TextBox and Combobox alternatively in GridComboBoxColumn. However, it is possible to achieve this by overriding the OnInitializeEditElement method in GridComboBoxCellRenderer.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Remove existing ComboBox Renderer
this.sfDataGrid1.CellRenderers.Remove("ComboBox");
//Add customized ComboBox Renderer
this.sfDataGrid1.CellRenderers.Add("ComboBox", new GridComboBoxCellRendererExt(sfDataGrid1));
}
}
public class GridComboBoxCellRendererExt : GridComboBoxCellRenderer
{
private SfDataGrid dataGrid;
public GridComboBoxCellRendererExt(SfDataGrid dataGrid) : base()
{
this.dataGrid = dataGrid;
}
protected override void OnInitializeEditElement(DataColumnBase column, RowColumnIndex rowColumnIndex, SfComboBox uiElement)
{
base.OnInitializeEditElement(column, rowColumnIndex, uiElement);
if (column.GridColumn.MappingName == "ShipCityID")
{
//ShipCity Column display the TextBox cell and ComboBox alternative rows in SfDataGrid
//Display the text box to edit the cell value instead of the combo box condition based.
if (rowColumnIndex.RowIndex % 2 == 0)
{
//To display the edit element as text box.
uiElement.DropDownStyle = DropDownStyle.DropDown;
uiElement.DropDownButton.Visible = false;
}
}
}
}As we have disabled the dropdown button of the ComboBox it is displayed like a textbox. But GridComboBoxColumn doesn't have support to accept the typed value which does not exist in the ComboBox list. However, it is possible to achieve this requirement by adding the newly typed value to the ComboBox list using the SfDataGrid.CurrentCellValidating event.
this.sfDataGrid1.CurrentCellValidating += sfDataGrid1_CurrentCellValidating;
void sfDataGrid1_CurrentCellValidating(object sender, CurrentCellValidatingEventArgs e)
{
if (this.sfDataGrid1.CurrentCell.Column is GridComboBoxColumn && this.sfDataGrid1.CurrentCell.CellRenderer.CurrentCellRendererElement != null)
{
var shipCityName = this.sfDataGrid1.CurrentCell.CellRenderer.CurrentCellRendererElement.Text;
var shipCityDetails = orderInfo.ShipCityDetails.FirstOrDefault(city => city.ShipCityName == shipCityName);
if (shipCityDetails == null && !string.IsNullOrEmpty(this.sfDataGrid1.CurrentCell.CellRenderer.CurrentCellRendererElement.Text))
{
shipCityID++;
orderInfo.ShipCityDetails.Add(new ShipCityDetails() { ShipCityName = this.sfDataGrid1.CurrentCell.CellRenderer.CurrentCellRendererElement.Text, ShipCityID = shipCityID });
}
}
}Take a moment to peruse the WinForms DataGrid – Customize Column Renderer documentation, where you can find about customize column renderer with code examples.
Visual Studio 2015 and above versions
