tags:

views:

1012

answers:

2

Hi, I am trying to define a multicolumn listview in xaml (visual studio 2008) and then add items to it in c#. I have seen many posts on this subject, and tried the various methods, but I am getting errors.

my xaml code is below, VS does not flag any errors on it.

<ListView Height="234.522" Name="chartListView" Width="266.337">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Name" Width="70"/>
      <GridViewColumn Header="ID" />
    </GridView>
  </ListView.View>
</ListView>

to try and add data to the columns, I created a button and put the code in the button click :

    private void button3_Click(object sender, RoutedEventArgs e)
    {
        chartListView.Items.Add("item1").SubItems.Add("item2");
    }

the error that is showing is on Subitems is:

'int' does not contain a definition for 'SubItems' and no extension method 'SubItems' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) D:\devel\VS\pchart\pchart\pchart\Window1.xaml.cs

Also, I tried looking at some other posts on listview controls such as

http://stackoverflow.com/questions/1260812/listview-inserting-items

i tried the code there :

ListViewItem item = new ListViewItem(); item.Text=anInspector.getInspectorName().ToString();

and got almost the same error on item.Text as i did with SubItems. is there something earlier in my code, or project definition that i am missing?

Thanks for any help

+1  A: 

There is no such thing as "sub-items" in WPF ListView (maybe you're confusing it with Windows Forms ListView). The Items property returns a collection of objects anyway, and object doesn't have a SubItems property. Actually, each item in the ListView may have multiple properties, and you specify which one you want to display with the DisplayMemberBinding property :

XAML

<ListView Height="234.522" Name="chartListView" Width="266.337">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="70"/>
      <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" />
    </GridView>
  </ListView.View>
</ListView>

C# :

private void button3_Click(object sender, RoutedEventArgs e)
{
    chartListView.Items.Add(new { Name = "test1", ID = "test2" });
}

(it doesn't have to be anonymous objects, you can use named classes of course...)

Thomas Levesque
hey thanks, just what I was looking for.
Will
A: 

When I tried your method to add items to a list view, for some reasons I can not select individual row. Only the first row can only be selected (highlighted). Do you know the reasons for that?

Andy