|
1 | | -# how-to-add-the-button-and-text-in-gridtextcolumn-in-winforms-datagrid |
2 | | -How to add the Button and Text in GridTextColumn in WinForms DataGrid (SfDataGrid)? |
| 1 | +# How to add the button and text in gridtextcolumn in WinForms DataGrid |
| 2 | + |
| 3 | +This repository describes how to add the Button and Text in `GridTextColumn` in [WinForms DataGrid](https://www.syncfusion.com/winforms-ui-controls/datagrid) (SfDataGrid). |
| 4 | + |
| 5 | +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](https://help.syncfusion.com/cr/Syncfusion.WinForms.DataGrid.Renderers.GridTextBoxCellRenderer.html). In the custom renderer, the `OnRender` method can be overridden to draw buttons in the cells. |
| 6 | + |
| 7 | +``` csharp |
| 8 | +public class GridTextButtonCellRenderer : GridTextBoxCellRenderer |
| 9 | +{ |
| 10 | + public GridTextButtonCellRenderer(SfDataGrid dataGrid) |
| 11 | + { |
| 12 | + IsEditable = true; |
| 13 | + DataGrid = dataGrid; |
| 14 | + } |
| 15 | + |
| 16 | + protected override void OnRender(Graphics paint, Rectangle cellRect, string cellValue, CellStyleInfo style, DataColumnBase column, RowColumnIndex rowColumnIndex) |
| 17 | + { |
| 18 | + base.OnRender(paint, cellRect, cellValue, style, column, rowColumnIndex); |
| 19 | + |
| 20 | + //To set the rectangle for button in the cell. |
| 21 | + var rect = new Rectangle(cellRect.Location.X + cellRect.Width - 22, cellRect.Location.Y, 20, cellRect.Height); |
| 22 | + |
| 23 | + (column.GridColumn as GridTextButtonColumn).CellButton = new CellButton(); |
| 24 | + (column.GridColumn as GridTextButtonColumn).CellButton.Image = Image.FromFile(@"..\..\Images\icons.png"); |
| 25 | + (column.GridColumn as GridTextButtonColumn).CellButton.TextImageRelation = TextImageRelation.ImageBeforeText; |
| 26 | + |
| 27 | + PropertyInfo highlightedItemProperty = (column.GridColumn as GridTextButtonColumn).CellButton.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).Single(pi => pi.Name == "Bounds"); |
| 28 | + highlightedItemProperty.SetValue((column.GridColumn as GridTextButtonColumn).CellButton, rect); |
| 29 | + |
| 30 | + //To draw the button in cell |
| 31 | + DrawButton(paint, cellRect, rect, "...", new ButtonCellStyleInfo(), column, rowColumnIndex); |
| 32 | + } |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +``` csharp |
| 37 | +//To add custom renderer into SfDataGrid. |
| 38 | +this.sfDataGrid.CellRenderers.Add("TextButton", new GridTextButtonCellRenderer(this.sfDataGrid)); |
| 39 | + |
| 40 | +//To add TextButtonColumn in grid |
| 41 | +this.sfDataGrid.Columns.Add(new GridTextButtonColumn() { MappingName = "CustomerID", Width = 140 }); |
| 42 | +``` |
| 43 | + |
| 44 | + |
0 commit comments