Question

Big question I've got a WPF usercontrol. It is using a ComponentOne gridview, so I don't know if that will cause any problems. Anyway, my gridview is declared thus:

<c1:C1DataGrid
    CanUserAddRows="False"
    ItemsSource="{Binding studentList}"
    SelectedItem="{Binding selectedStudent}">
    <c1:C1DataGrid.Columns>
        <c1:DataGridTextColumn
            Header="Student"
            Binding="{Binding Student}"
            Width="Auto"/>
        <c1:DataGridTextColumn
            Header="Age"
            Binding="{Binding Age}"
            Width="Auto"/>
        <c1:DataGridTemplateColumn Header="Class" Width="Auto">
            <c1:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Class}"/>
                </DataTemplate>
            </c1:DataGridTemplateColumn.CellTemplate>
            <c1:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Class}"/>
                </DataTemplate>
            </c1:DataGridTemplateColumn.CellEditingTemplate>
            </c1:DataGridTemplateColumn>
        </c1:C1DataGrid.Columns>
    </c1:C1DataGrid>

Using MVVM, my data comes from the users input on the form. Once the user has pressed the Add button, the data is filled into the gridview as you see it. The Class column is an editable column, as the user my want to change something in there before they save. Now, my gridview has a SelectedItem control, bound to selectedStudent. Ideally, the user selects a student they want removed, click Delete and it is removed. In my ViewModel code, I fill the gridview using an observable list. Thus:

studentList.Add(new Student()
    {
        Name = Name,
        Age = Age,
        Class = Class
    });
    OnPropertyChanged(null);

Student is the table. I use a list to display the items entered into the gridview. How do I remove a selected item? I instantiate the selectedStudent in code:

public Student = selectedStudent { get; set; }
selectedStudent = new Student();

I have tried to code:

studentList=studentList.Any(i=>i.Name!=selectedStudent.Name);

but I know I'm wrong here. I don't fully understand the power of LINQ or Lambda. What do I use to remove? And how do I get the selected item? Is that a variable? Or something else?

Was it helpful?

Solution

You just need to use the Remove method in the list as you already have the selected student object.

 studentList.Remove(selectedStudent);

if this doesn't remove then selectedStudent may not be part of the actual list, in that case you can try the following by finding the item from the list which has matching Name as the selectedStudent

studentList.Remove(studentList.FirstOrDefault(p=>p.Name == selectedStudent.Name));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top