Hello, I am kinda new to Vb.net and I need some help regarding listview.
I want to add a certain value at a certain location for a listview. Like adding a new row at the current selected area.
What the program do as of now was to add new rows at location 0.
can anyone help me..
What do you mean by new row at the currently selected area ? Can you be a little more clear on that ?
ListView object won't add rows at location 0, as far as I know. Instead it would put it at the bottom.
If you mean that you want to add a row ABOVE or BELOW a single or a set of items in the listview, then you can take the following approach:
For a ListView you can set it's property MultiSelect
. If so, an user might select a single row or multiple rows at a time. If set to false
a user ca select only a SINGLE line.
Say, I want to insert a row below a selected row.
There's a method called SelectedIndices()
under ListView class which returns an array containing the Index of the selected items in the list. The index of the first item is ZERO.
Now in case MultiSelect is set to false - SelectedIndices will return only a single row, but when MultiSelect is true, this will return an array.
If false, we can get the selected row (lets say, Max) by simply looking for it's index in the SelectedIndices() array's position ZERO - why we can be sure that this item will be in position ZERO is - that this array will containing ONLY ONE item, based on MultiSelect to be false.
So two cases:
Case 1: MultiSelect = false
Dim Max as Integer = lsvReceipts.SelectedIndices.Item (0)
Case 2: MultiSelect = true
If not, from that array you have to determine the highest index
of the SelectedItems, to know which position you've to insert this new value.
Lets use a short example with this list of receipts ( lsvReceipts ):
'We start by creating a variable called Max and store the first index in
Dim Max As Integer = lsvReceipts.SelectedIndices.Item(0)
'We go through the SelectedIndices Array and find the highest index stored in it.
'We loop through 0 to SelectedIndices.Count - 1, as we're counting from '0' .
For Counter = 0 To lsvReceipts.SelectedIndices.Count - 1
'Check with the item in each position - see if it's greater than Max
If Max < lsvReceipts.SelectedIndices.Item(Counter) Then
'Set Max equal to it
Max = lsvReceipts.SelectedIndices.Item(Counter)
'Now we know the Index of the Last Selected Item ( stored in Max )
So armed with the last selected item's position, we ADD
a '1' to it, since what we want to insert, goes at a position below it. So
'Increase Max by '1'
Max += 1
Now, simply issue an insert statement:
'Insert new item at that position.
lsvReceipts.Items.Insert ( Max, "New Item" )
There you go...