开发者

Windows Forms - How to access ListView's SubItems by column name?

I've tried this but it's giving me 'System.NullReferenceException':

    For Each MyListViewItem As ListViewItem In MyListView.Items
        MsgBox(MyListViewItem.SubItems("MyColumn").Text)
    Next

These lines of codes work (weird!):

    For Each MyListViewItem As ListViewItem In MyListView.Items
        MsgBox(MyListViewItem.SubItems(0).Text)
    Next

But I need to access them by column name.

I found that this code gives me blank subitem name

For Each MyListViewItem As ListViewItem In MyListView.Items
    MsgBox(MyListViewItem.SubItems(0).Name)
Next

Note that I added the columns in design time. While items in run-time:

    While Reader.Read
        Dim SubItems(2) As String
        SubItems(0) = Reader("ItemForMyColumn")
  开发者_StackOverflow      SubItems(1) = Reader("ItemForSomeOtherColumn")
        MyListView.Items.Add(New ListViewItem(SubItems))
    End While

Thanks in advance!


It is likly throwing the null reference exception when trying to access the Text property on the SubItems("MyColumn") part of your sample.

You could check to see if MyListViewItem.SubItems("MyColumn") is not null before trying to read the Text property from it.

It could also be (based on your edit) that the name you are using to look it up doesn't match that's in the SubItems list.

If you print the name that you are looking for by using the index, what do you see?

After Edits

I might be this wrong, but it looks like by using this constructor for the ListViewItem, it's only going to be getting the Text property set.

I suggest trying something like this in your init code for the ListViewItem

(Forgive me, my VB is really really rusty and I don't have VS open)

While Reader.Read
   Dim listViewItem As New ListViewItem()

   Dim subItem1 As New ListViewSubItem()
   subItem.Text = Reader("ItemForMyColumn")
   subItem1.Name = "MyColumn"

   //Do this as many times as you need

   listViewItem.SubItems.Add( subItem1 )

   MyListView.Items.Add( listViewItem )    
End While


I think the you can get any subitems by its name as below:

When add columns dynamically

ListView1.Column.Add(dr("attribute_name"),dr("attribute_label"),dr("attribute_width"))

Then when get any subitems

ListView1.SelectedItems.Item(0).SubItems(ListView1.Column("attribute_name").Index).Text
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜