简体   繁体   中英

How to fill listview in WPF C#

I`m trying to fill list view on window loaded event but Nothing comes out.

This is my XAML

<ListView Height="142" Name="listView1" Width="371">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="60" Header="ID"/>
                    <GridViewColumn Width="300" Header="User Name" />
                </GridView>
            </ListView.View>
        </ListView>
    </GroupBox>

this my c# code:

  private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        ArrayList _ID = new ArrayList();
        ArrayList _UserList = new ArrayList();

        using (DataClasses1DataContext dc = new DataClasses1DataContext())
        {
            var Users = (from u in dc.users select u.username).ToList();

            for (int i = 0; i < Users.Count(); i++)
            {
                _UserList.Add(Users[i]).ToString();
            }


            using (DataClasses1DataContext dcc = new DataClasses1DataContext())
            {
                var ID = (from u in dcc.users select u.id).ToList();

                for (int i = 0; i < ID.Count(); i++)
                {
                    _ID.Add(ID[i]).ToString();
                }

            }
        }

Please help

GridViewColumns work via the DisplayMemberBinding or the CellTemlate . You specify neither.

Further i do not see you reference the ListView in your code at all, at the very least you would need to add items via ListView.Items.Add or by setting the ListView.ItemsSource .

First make on object, i see you have 2 different lists. Just use one object, keeping both data. Next, like HB said, you need to specify what each columns shows. The simple way is to use DisplayMemberPath , the more complex but also more flexible solution is to use a specialized CellTemplate .

if your data object looks like this

public class MyObject
{
   public int Id{get;set;}
   public string Name {get;set;}
}

your ListView holding a list of these items in xaml would look like.

<ListView.View>
    <GridView>
        <GridViewColumn Width="60" Header="ID" DisplayMemberBinding="{Binding Id}"/>
        <GridViewColumn Width="300" Header="User Name" DisplayMemberBinding="{Binding Name}" />
    </GridView>
</ListView.View>

Hope that helps.

Well ListView1 ist not bound to any datasource.

also the generated arrays are never assigned to the list view....

Have a look at the ItemSource Property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM