1

I'm trying to display data from my Entitity Framework database to my ListView in my WPF C# application.

I'm using WCF app as my host, where I keep my methods for displaying data, adding data, etc., and I have WPF app as my client, where I use the code to display data from database to my ListView.

This is my code

ServiceReference1.ImojWCFServiceClient client = new ServiceReference1.ImojWCFServiceClient();
listView1.Items.Clear();
var userList = client.getUsers();
foreach (var user in userList)
{
   ListViewItem listOfUsers;
   string[] list = new string[3];
   list[0] = user.UserID.ToString();
   list[1] = user.Name;
   list[2] = user.LastName;
   listOfUsers = new ListViewItem(list);
   listView1.Items.Add(listOfUsers);
}

This is the error that I get enter image description here

Can somebody help me fix this code?

Any help is appreciated!

0

2 Answers 2

4

If your getUsers method returns a list, array, or similar, you could simply set the ItemsSource of the ListView to userList. For example:

ServiceReference1.ImojWCFServiceClient client = new ServiceReference1.ImojWCFServiceClient();
listView1.Items.Clear();
var userList = client.getUsers();
listView1.ItemsSource = userList;

If that doesn't work, convert userList to an ObservableCollection before setting the ItemsSource

Your Xaml might look like this...

<ListView>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding UserID}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
            <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}"/>
        </GridView>
    </ListView.View>
</ListView>
Sign up to request clarification or add additional context in comments.

Comments

1

ListViewItem doesn't have a constructor that takes one argument. So listOfUsers = new ListViewItem(list); isn't going to work.

Try an approach like this:

var items = new List<User>();
items.Add(new User() { Name = "John Doe", Age = 42 });
items.Add(new User() { Name = "Jane Doe", Age = 39 });
items.Add(new User() { Name = "Sammy Doe", Age = 13 });
myListView.ItemsSource = items;

3 Comments

It's just an example. You have to substitute your own use case. It's not copy/paste code.
Actually it is copy and paste code from here: stackoverflow.com/questions/25862244/sorting-data-in-listview
@startoftext: That's not what I meant by copy/paste code. By copy/paste code, I mean trying to cobble together a program by copy/pasting code snippets from the Internet. Real programmers actually write code that meets their specific needs!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.