title: fill listview2 based on checked item in listview1 from database in vb.net
body: <p>I need to populate listview2 based on checked items of listview1</p>
  <p>I have tried the code but its filling listview2 item when I uncheck the item from listview1</p>
  <pre class="lang-vb prettyprint-override"><code>Private Function selectionfromDeptTofillLv2() As Boolean 
      Dim i As Integer, Yn As Boolean
      Yn = False
      Dim strDept As String = &quot;&quot;
      For i = 0 To ListView1.Items.Count - 1
          ListView1.Items(i).Selected = True
          If ListView1.Items(i).Checked = True Then
              If Trim(strDept) &lt;&gt; &quot;&quot; Then strDept = strDept &amp; &quot;,&quot;
              strDept = strDept &amp; Trim(ListView1.Items(i).Tag)
              Yn = True
          End If
      Next
      
      If Yn = True Then
          Dim strSQL As String = &quot;&quot;, strSQLdept As String = &quot;&quot;
  
          conn = GetConnect()
          conn.Open()
  
          strSQL = &quot;select SubName,SubDeptID from DepartmentSub where active=1&quot;
          If Trim(strDept) &lt;&gt; &quot;&quot; Then strSQLdept = strSQLdept &amp; &quot; And DepartmentID In (&quot; &amp; strDept &amp; &quot;)&quot; &amp; &quot; order by SubName&quot;
  
          strSQL = strSQL &amp; strSQLdept
          'MsgBox(strSQL)
          Dim cmd3 As SqlCommand = New SqlCommand(strSQL, conn)
          Dim sda3 As SqlDataAdapter = New SqlDataAdapter(cmd3)
          Dim dt3 As DataTable = New DataTable()
  
          sda3.Fill(dt3)
  
          With ListView2
              ListView3.Clear()
              .Clear()
              .View = View.Details
              .GridLines = True
              .Columns.Clear()
              .Items.Clear()
              .Columns.Add(&quot; &quot;, 30)
              .Columns.Add(&quot;Sub Department Name&quot;, 250, HorizontalAlignment.Left)
  
              For Each row As DataRow In dt3.Rows
                  'Add Item to ListView.
                  Dim item As ListViewItem = New ListViewItem
                  item.SubItems.Add(row(&quot;SubName&quot;).ToString())
                  item.Tag = Val(row(&quot;SubDeptID&quot;).ToString)
                  item.Checked = False
                  .Items.Add(item)
                  item = Nothing
              Next
          End With
      End If
      conn.Close()
  End Function
  
  'selectall in listview1
  Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.Click
      For Each lvitem As ListViewItem In Me.ListView1.Items
          lvitem.Checked = CheckBox2.Checked
      Next
      selectionfromDeptTofillLv2()
  End Sub
  
  'calling sub from listview1 below
  Private Sub ListView1_MouseUp(sender As Object, e As MouseEventArgs) Handles ListView1.MouseUp
      selectionfromDeptTofillLv2()
  End Sub
  </code></pre>