none
Delete ListView RRS feed

  • Question

  • hi all,

    Listview and Textboxes

    sr.No|ProductName |Price

    1      | Apple           | 10$

    2      |Orange          | 5$

    3      |Grapes           | 3$

    4      | Peach            | 2$

    ------------------------------------------

    Total                          20$

    Problem Statement.

    i want to delete the  sr.no: 2, Orange Product,  I want the whole listview Rearrange and Price Total will be recounted. Now list Look as or Required Out Pur

    sr.No|ProductName |Price

    1      | Apple           | 10$

    2      |Grapes           | 3$

    3      | Peach            | 2$

    ------------------------------------------

    Total                          15$

       If e.KeyCode = Keys.Delete Then
                'Delete Selected Items
                For i As Integer = ListView1.SelectedItems.Count - 1 To 0 Step -1
                    ListView1.SelectedItems(i).Remove()
                Next
               
                'Clear Previously selected Items
                ListView1.SelectedItems.Clear()
                'Highlight only when there are items

    Thanks

                                   


    MUHAMMAD ANZAR E-mail : muhammadanzar@hotmail.com Mobile # :0092-3215096959



    Monday, December 23, 2019 4:58 PM

All replies

  • hi,

    i only use the listview,  i show the data in listview,  All the data When correct in listview at the end save it in database


    MUHAMMAD ANZAR E-mail : muhammadanzar@hotmail.com Mobile # :0092-3215096959

    Monday, December 23, 2019 6:21 PM
  • Hi

    Try this

    ' Form1 with ListView1
    ' Button1, Label1
    Option Strict Off
    Option Explicit On
    Public Class Form1
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		With ListView1
    			.Bounds = New Rectangle(New Point(10, 10), New Size(500, 200))
    			' Set to details.
    			.View = View.Details
    			' Allow item edit.
    			.LabelEdit = True
    			' Allow rearrange columns.
    			.AllowColumnReorder = False
    			' check boxes.
    			.CheckBoxes = False
    			' Select whole row.
    			.FullRowSelect = True
    			' Show grid lines.
    			.GridLines = True
    			.LabelWrap = False
    			ListView1.Columns.Add("Item", 60, HorizontalAlignment.Left)
    			.Columns.Add("Product", 140, HorizontalAlignment.Left)
    			.Columns.Add("Price", 60, HorizontalAlignment.Left)
    
    			' make some test data
    			Dim rand As New Random
    			Dim itms As New List(Of String)
    			itms.AddRange({"Apple", "Grape", "Peach", "Banana", "Astical", "Pomegranate", "Orange", "Tomato", "BlueBerry", "Plum"})
    			For itm As Integer = 1 To 10
    				Dim item As New ListViewItem(itm.ToString)
    				item.SubItems.Add(itms(itm - 1))
    				item.SubItems.Add(rand.Next(20, 50))
    				.Items.Add(item)
    			Next
    		End With
    		Label1.Text = Total()
    	End Sub
    	Sub Renumber()
    		Dim c As Integer = 1
    		For Each r As ListViewItem In ListView1.Items
    			r.SubItems(0).Text = c.ToString
    			c += 1
    		Next
    	End Sub
    	Function Total() As String
    		Dim tot As Integer = 0
    		For Each r As ListViewItem In ListView1.Items
    			Dim v As Integer = 0
    			Integer.TryParse(r.SubItems(2).Text, v)
    			tot += v
    		Next
    		Return tot.ToString
    	End Function
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		If ListView1.SelectedIndices.Count < 1 Then Exit Sub
    		ListView1.Items.RemoveAt(ListView1.SelectedIndices(0))
    		Label1.Text = Total()
    		Renumber()
    	End Sub
    End Class


    Regards Les, Livingston, Scotland

    Monday, December 23, 2019 7:54 PM
  • Hi,

    Leshay has provided you with a great solution that can help you recount the whole listview.

    I am a little confused about the following points, and want to wait for your explanation:

    1.Are these TextBox used for what? For insert data to ListView?

    2.Where are the initial data come from? Is it Database?

    3. Do you save data into the database while removing the data? If so, which column do you use as the table's primary key? Is it sr.No or ProductName?

    Best Regards,

    Julie


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.



    Tuesday, December 24, 2019 2:46 AM
    Moderator
  • Hi,

    This is what I understand your intention, I don't know if it matches your idea.


    If so, you can try my code like this:

    Imports System.Data.SqlClient
    
    Public Class Form1
        Dim constr As String = "Data Source = (localdb)\MSSQLLocalDB; Integrated Security = True ;AttachDbFileName= D:\Local Database\191224.mdf"
        Dim selectno As Integer
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using conn = New SqlConnection(constr)
                conn.Open()
                Dim cmd As New SqlCommand
                cmd.Connection = conn
                cmd.CommandText = "SELECT Max(srno) FROM Product"
                cmd.ExecuteNonQuery()
                Dim maxno As Integer = cmd.ExecuteScalar
    
                Dim sql As String = "insert into Product values('{0}','{1}','{2}')"
                sql = String.Format(sql, maxno + 1, TextBox1.Text.Trim, TextBox2.Text.Trim)
                cmd = New SqlCommand(sql, conn)
                cmd.ExecuteNonQuery()
    
            End Using
    
            ShowProductData()
        End Sub
    
        Sub ShowProductData()
            Try
                ListView1.FullRowSelect = True
                Using conn As New SqlConnection(constr)
                    conn.Open()
                    Dim cmd As New SqlCommand("SELECT * FROM Product", conn)
                    Dim sda As New SqlDataAdapter
                    sda.SelectCommand = cmd
                    Dim dt As New DataTable
                    sda.Fill(dt)
    
                    Dim RowCount, ColCount, i, j As Integer
                    Dim dr As DataRow = Nothing
                    If dt Is Nothing Then Return
                    RowCount = dt.Rows.Count
                    ColCount = dt.Columns.Count
    
    
                    ListView1.Clear()
                    ListView1.View = View.Details
                    ListView1.AllowColumnReorder = True
                    ListView1.GridLines = True
    
                    For i = 0 To ColCount - 1
                        ListView1.Columns.Add(dt.Columns(i).Caption.Trim(), 100, HorizontalAlignment.Left)
    
                    Next
    
                    If RowCount = 0 Then Return
                    For i = 0 To RowCount - 1
                        dr = dt.Rows(i)
                        ListView1.Items.Add(dr(0).ToString().Trim())
    
                        For j = 1 To ColCount - 1
                            ListView1.Items(i).SubItems.Add(CStr(dr(j).ToString().Trim()))
                        Next
                    Next
    
                    cmd.CommandText = "SELECT sum(price) FROM Product"
                    cmd.ExecuteNonQuery()
                    Dim totalprice As Double = cmd.ExecuteScalar
                    TextBox3.Text = totalprice
    
                End Using
            Catch ex As Exception
            End Try
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ShowProductData()
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            If ListView1.SelectedIndices.Count < 1 Then Exit Sub
    
            Using conn = New SqlConnection(constr)
                conn.Open()
    
                Dim cmd As New SqlCommand
                cmd.Connection = conn
                cmd.CommandText = "SELECT count(srno) FROM Product"
                cmd.ExecuteNonQuery()
                Dim count = cmd.ExecuteScalar
    
                If selectno = count Then
                    cmd = New SqlCommand("delete from Product where srno=@srno", conn)
                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("@srno", selectno)
                    cmd.ExecuteNonQuery()
                    MsgBox("delete OK!")
                End If
    
                While (selectno < count)
    
                    selectno += 1
                    cmd.CommandText = "SELECT ProductName FROM Product where srno=@srno"
                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("@srno", selectno)
                    cmd.ExecuteNonQuery()
                    Dim ProductName As String = cmd.ExecuteScalar
    
                    cmd.CommandText = "SELECT Price FROM Product where srno=@srno"
                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("@srno", selectno)
                    cmd.ExecuteNonQuery()
                    Dim Price As Double = cmd.ExecuteScalar
    
    
                    cmd = New SqlCommand("update Product set ProductName=@ProductName,Price=@Price where srno=@srno", conn)
                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("@srno", selectno - 1)
                    cmd.Parameters.AddWithValue("@ProductName", ProductName)
                    cmd.Parameters.AddWithValue("@Price", Price)
                    cmd.ExecuteNonQuery()
    
                    If selectno = count Then
                        cmd = New SqlCommand("delete from Product where srno=@srno", conn)
                        cmd.Parameters.Clear()
                        cmd.Parameters.AddWithValue("@srno", selectno)
                        cmd.ExecuteNonQuery()
                        MsgBox("delete OK!")
                    End If
    
                End While
                ShowProductData()
            End Using
        End Sub
    
        Private Sub ListView1_ItemSelectionChanged(sender As Object, e As ListViewItemSelectionChangedEventArgs) Handles ListView1.ItemSelectionChanged
            If e.IsSelected Then selectno = e.Item.SubItems(0).Text
        End Sub
    End Class

    If not, please feel free to connect us.

    Hope it be helpful.

    Best Regards,

    Julie



    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.



    Tuesday, December 24, 2019 7:39 AM
    Moderator
  • Hi

    Here is a version using a ContextMenuStrip to REMOVE multi-selected items.

    ' Form1 with ListView1
    ' Label1
    ' using ContextMenuStrip
    ' to REMOVE itemsd
    Option Strict Off
    Option Explicit On
    Public Class Form1
    	Dim WithEvents ContextMenuStrip1 As New ContextMenuStrip
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		Dim menu1 As New ToolStripMenuItem() With {.Text = "Delete SELECTED items", .Name = "delselitems"}
    		ContextMenuStrip1.Items.Add(menu1)
    
    		With ListView1
    			.ContextMenuStrip = ContextMenuStrip1
    			.Bounds = New Rectangle(New Point(10, 10), New Size(500, 200))
    			' Set to details.
    			.View = View.Details
    			' Allow item edit.
    			.LabelEdit = True
    			' Allow rearrange columns.
    			.AllowColumnReorder = False
    			' check boxes.
    			.CheckBoxes = False
    			' Select whole row.
    			.FullRowSelect = True
    			' Show grid lines.
    			.GridLines = True
    			' allow multi select
    			.MultiSelect = True
    			.LabelWrap = False
    			ListView1.Columns.Add("Item", 60, HorizontalAlignment.Left)
    			.Columns.Add("Product", 140, HorizontalAlignment.Left)
    			.Columns.Add("Price", 60, HorizontalAlignment.Left)
    
    			' make some test data
    			Dim rand As New Random
    			Dim itms As New List(Of String)
    			itms.AddRange({"Apple", "Grape", "Peach", "Banana", "Astical", "Pomegranate", "Orange", "Tomato", "BlueBerry", "Plum"})
    			For itm As Integer = 1 To 10
    				Dim item As New ListViewItem(itm.ToString)
    				item.SubItems.Add(itms(itm - 1))
    				item.SubItems.Add(rand.Next(20, 50))
    				.Items.Add(item)
    			Next
    		End With
    		Label1.Text = Total()
    	End Sub
    	Sub Renumber()
    		Dim c As Integer = 1
    		For Each r As ListViewItem In ListView1.Items
    			r.SubItems(0).Text = c.ToString
    			c += 1
    		Next
    	End Sub
    	Function Total() As String
    		Dim tot As Integer = 0
    		For Each r As ListViewItem In ListView1.Items
    			Dim v As Integer = 0
    			Integer.TryParse(r.SubItems(2).Text, v)
    			tot += v
    		Next
    		Return tot.ToString
    	End Function
    	Private Sub ContextMenuStrip1_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles ContextMenuStrip1.ItemClicked
    		If ListView1.SelectedIndices.Count < 1 Then Exit Sub
    		' Remove ALL selected items
    		For i As Integer = ListView1.SelectedItems.Count - 1 To 0 Step -1
    			ListView1.Items.RemoveAt(ListView1.SelectedIndices(i))
    		Next
    		Label1.Text = Total()
    		Renumber()
    	End Sub
    End Class


    Regards Les, Livingston, Scotland

    Tuesday, December 24, 2019 4:44 PM