Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd new row to Datagrid in a UserControl WPF/VB
    primarykey
    data
    text
    <p>I'm trying to create a UserControl which consists of a DataGrid and a couple of buttons. The buttons will handle adding/deleting rows (needs to be buttons). The DataGrid is bound to a custom observable collection. The collections properties will vary (so I'm auto-generating the columns).</p> <p>How can I add a new row? Normally I'd just modify the observable collection. I've tried adding a new row directly to the control:</p> <pre><code>dgMain.Items.Add(New DataGridRow()) </code></pre> <p>but I get an error which doesn't mean much to me:</p> <blockquote> <p>Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.</p> </blockquote> <p>Here's the current code behind:</p> <pre><code>Public Class DataGrid Sub New() InitializeComponent() End Sub #Region "Dependency Properties" Public Shared MyItemsSourceProperty As DependencyProperty = DependencyProperty.Register("MyItemsSource", GetType(IEnumerable), GetType(DataGrid)) Public Property MyItemsSource() As IEnumerable Get Return DirectCast(GetValue(MyItemsSourceProperty), IEnumerable) End Get Set(value As IEnumerable) SetValue(MyItemsSourceProperty, value) End Set End Property #End Region #Region "Buttons" Private Sub btnAdd_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btnAdd.Click dgMain.Items.Add(New DataGridRow()) End Sub #End Region End Class </code></pre> <p>So does anyone know how I can add a new row?</p> <p>Thanks for any help.</p> <p>EDIT: This is how the data is created:</p> <pre><code>Dim np As New ObPerson np.Add(New Person With {.FirstName = "Jane", .LastName = "Mitel", .Age = 18}) np.Add(New Person With {.FirstName = "Joe", .LastName = "Bloggs", .Age = 92}) UserControlInstance.MyItemsSource = np Public Class ObPerson Inherits ObservableCollection(Of Person) End Class </code></pre> <p>EDIT2: VB Version of the accepted answer:</p> <pre><code>Public Shared Sub AddNewElement(l As IList) If l Is Nothing OrElse l.Count = 0 Then Throw New ArgumentNullException() End If Dim obj As Object = Activator.CreateInstance(l(0).[GetType]()) l.Add(obj) End Sub Usage: AddNewElement(MyItemsSource) </code></pre>
    singulars
    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.
 

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