Refresh listview data on a button click

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Locked
User avatar
bush3102
Posts: 8
Joined: Thu Apr 05, 2018 7:24 am

Refresh listview data on a button click

Post by bush3102 »

I am using the following script, when I click on a button to run a SQL query (searching based on a text box), I have the results sent to a List View. When I change what is in the text box and click the button again, the results are added to the bottom of the previous list.

When I add "-Clear" to Add-ListViewItem and click the button, only 1 record appears in the List View. What do I need to do to clear the List View before populating with new data?

Code: Select all

$button1_Click={
	#TODO: Place custom script here
	Get-DBlist -DBSearch $global:DBName
}

$textbox1_TextChanged={
	#TODO: Place custom script here
	$global:DBName = $textbox1.text
}

Function Get-DBList
{
	param (
		[CmdletBinding()]
		[Parameter(Mandatory = $false, Position = 1)]
		[String]$DBSearch
		
	)
	
	$server = "sqlserver,1433"
	$QueryCMS = "
                    SELECT 
                    servername
                    ,database_name
                    FROM Database.Table
                    WHERE
                    name like '%$DBSearch%'
                    and state_desc = 'Online'
                    and
                    name not in ('master','model','msdb','tempdb')
                    order by 1,2            
            "
	
	Invoke-Sqlcmd -ServerInstance $server -query $QueryCMS |
	ForEach-Object{
		Add-ListViewItem -ListView $listview1 -Items $_.servername -SubItems $_.database_name -Clear
	}
}

User avatar
Alexander Riedel
Posts: 7601
Joined: Tue May 29, 2007 4:43 pm
Answers: 2
Been upvoted: 6 times

Re: Refresh listview data on a button click

Post by Alexander Riedel »

In your ForEach-Object loop you add an item and by using -Clear you erase any items before. So you'll only see the last item.
Call $listview1.Clear() before your loop.
Alexander Riedel
SAPIEN Technologies, Inc.

User avatar
bush3102
Posts: 8
Joined: Thu Apr 05, 2018 7:24 am

Re: Refresh listview data on a button click

Post by bush3102 »

I ended up adding

Code: Select all

$listview1.Items.Clear()
before the function was called to clear out the items from the List View

Code: Select all

$button1_Click={
	#TODO: Place custom script here
	$listview1.Items.Clear()
	Get-DBlist -DBSearch $global:DBName
}

Locked