Some times we need to add some controls in a container at run time. Here is the coding logic given to add CheckBox column in Datagrid control dynamically at run time. This code logic is in context with WPF. for winforms the some classes may differ.
Example :
DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
dgTemplateColumn.Header = headerText;
FrameworkElementFactory factoryElementCheckBox = new FrameworkElementFactory(typeof(CheckBox));
factoryElementCheckBox.SetBinding(CheckBox.IsCheckedProperty, new System.Windows.Data.Binding(bindingName));
factoryElementCheckBox.SetValue(CheckBox.NameProperty, bindingName);
factoryElementCheckBox.SetValue(CheckBox.HorizontalAlignmentProperty, HorizontalAlignment.Left);
factoryElementCheckBox.SetValue(CheckBox.VerticalAlignmentProperty, VerticalAlignment.Center);
CheckBoxColumnElement.Add(factoryElementCheckBox);
DataTemplate dataTemplate = new DataTemplate();
dataTemplate.VisualTree = factoryElementCheckBox;
dgTemplateColumn.CellTemplate = dataTemplate;
dgTemplateColumn.IsReadOnly = isReadOnly;
dataGrid.Columns.Add(dgTemplateColumn);
Example :
DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
dgTemplateColumn.Header = headerText;
FrameworkElementFactory factoryElementCheckBox = new FrameworkElementFactory(typeof(CheckBox));
factoryElementCheckBox.SetBinding(CheckBox.IsCheckedProperty, new System.Windows.Data.Binding(bindingName));
factoryElementCheckBox.SetValue(CheckBox.NameProperty, bindingName);
factoryElementCheckBox.SetValue(CheckBox.HorizontalAlignmentProperty, HorizontalAlignment.Left);
factoryElementCheckBox.SetValue(CheckBox.VerticalAlignmentProperty, VerticalAlignment.Center);
CheckBoxColumnElement.Add(factoryElementCheckBox);
DataTemplate dataTemplate = new DataTemplate();
dataTemplate.VisualTree = factoryElementCheckBox;
dgTemplateColumn.CellTemplate = dataTemplate;
dgTemplateColumn.IsReadOnly = isReadOnly;
dataGrid.Columns.Add(dgTemplateColumn);
No comments:
Post a Comment
Put your comments here