Monday, December 15, 2008

Fill Listview Control Dynamically

Code to fill the listview control in vb.net dynamically

Dim rdGetData As SqlClient.SqlDataReader
Try
   If ListView1.Items.Count > 0 Then ListView1.Items.Clear()
   SQLCmd.CommandType = CommandType.Text
   SQLCmd.CommandText = "SELECT * from table"
   rdGetData = SQLCmd.ExecuteReader

   Dim intCount As Decimal = 0
   While rdGetData.Read
      ListView1.Items.Add(Trim("FieldName")) 'col no. 1
      ListView1.Items(CInt(intCount)).SubItems.Add(Trim
                     (rdGetContactsInfo("FieldName"))) 'col no. 2
      ListView1.Items(CInt(intCount)).SubItems.Add(Trim
                     (rdGetContactsInfo("FieldName"))) 'col no. 3
      intCount = intCount + 1
   End While
  
   rdGetData.Close()
   rdGetData = Nothing
  
   Catch Exp As Exception
      intNumError = Err.Number()
      MsgBox("[ " & CStr(intNumError) + " ] " + Err.Description,
      MsgBoxStyle.Critical, " (Program Error)")
   End Try

Code to get selected item in the textbox control into the button's click event or according to your requirment.

TextBox1.Text = ListView1.SelectedItems(0).Text
TextBox2.Text = ListView1.SelectedItems(0).SubItems(2).Text

This will copy the selected item's first value and 2nd value into the textboxes.

To display the selected text in the textbox.

Private Sub ListView1_ItemDrag(ByVal sender AsObject, 
          ByVal e As System.Windows.Forms.ItemDragEventArgs)
          Handles ListView1.ItemDrag
   TextBox1.Text = e.Item.ToString
End Sub

No comments:

Post a Comment