How to add the Button and Text in GridTextColumn in WinForms DataGrid (SfDataGrid)?
By default, you can add either text or button in a GridColumn but, you can add both button and text in a column by customizing GridTextBoxCellRenderer in WinForms DataGrid. In the custom renderer, the OnRender method can be overridden to draw buttons in the cells.
public class GridTextButtonCellRenderer : GridTextBoxCellRenderer
{
public GridTextButtonCellRenderer(SfDataGrid dataGrid)
{
IsEditable = true;
DataGrid = dataGrid;
}
protected override void OnRender(Graphics paint, Rectangle cellRect, string cellValue, CellStyleInfo style, DataColumnBase column, RowColumnIndex rowColumnIndex)
{
base.OnRender(paint, cellRect, cellValue, style, column, rowColumnIndex);
//To set the rectangle for button in the cell.
var rect = new Rectangle(cellRect.Location.X + cellRect.Width - 22, cellRect.Location.Y, 20, cellRect.Height);
(column.GridColumn as GridTextButtonColumn).CellButton = new CellButton();
(column.GridColumn as GridTextButtonColumn).CellButton.Image = Image.FromFile(@"..\..\Images\icons.png");
(column.GridColumn as GridTextButtonColumn).CellButton.TextImageRelation = TextImageRelation.ImageBeforeText;
PropertyInfo highlightedItemProperty = (column.GridColumn as GridTextButtonColumn).CellButton.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).Single(pi => pi.Name == "Bounds");
highlightedItemProperty.SetValue((column.GridColumn as GridTextButtonColumn).CellButton, rect);
//To draw the button in cell
DrawButton(paint, cellRect, rect, "...", new ButtonCellStyleInfo(), column, rowColumnIndex);
}
}//To add custom renderer into SfDataGrid.
this.sfDataGrid.CellRenderers.Add("TextButton", new GridTextButtonCellRenderer(this.sfDataGrid));
//To add TextButtonColumn in grid
this.sfDataGrid.Columns.Add(new GridTextButtonColumn() { MappingName = "CustomerID", Width = 140 });
Conclusion
I hope you enjoyed learning how to add the Button and Text in GridTextColumn in WinForms DataGrid (SfDataGrid).
You can refer to our WinForms DataGrid feature tour page to know about its other groundbreaking feature representations documentation
and how to quickly get started for configuration specifications. You can also explore our WinForms DataGrid example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!