Add Listview Item in a cell of Data Grid View

309 Views Asked by At

I have Listview in form1 having columns AccountID, AccountName and AccountType and Form2 Datagridview unbound columns are Date, DocNo AccountID, AccountName, Debit, Credit.

i need two things:

  1. when i select any row in listview and double click, only AccountID should be transferred in AccountID Cells of DatagridView and considering AccountID as Lookup value, Corresponding AccountName should also be displayed in AccountName Column of Datgirdview.

  2. if i enter AccountID manually in the AccountID Cell of DataGridView Corresponding AccountName should also be displayed in AccountName Column of Datgirdview

Please help me to solve this issue.

1

There are 1 best solutions below

4
Oak_3260548 On

First of all, you didn't tag your post with language and framework and didn't mentioned it either. I'm posting VB.NET winform solution.

  1. DoubleClick on ListView1:
Private Sub ListView1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles ListView1.MouseDoubleClick
    ' provided the ValueMember of this ListView is set to AccountID
    If Me.DataGridView1.SelectedRows.Count > 0 AndAlso Me.ListView1.SelectedItems.Count > 0 Then
        Me.DataGridView1.SelectedRows(0).Cells("AccountID").Value = CInt(Me.ListView1.SelectedItems(0).SubItems(0).Text)
    End If
End Sub
  1. Manual edit in DataGridView:
Private Sub dgRuns_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgRuns.CellEndEdit
    If e.ColumnIndex = 0 Then   ' Only if AccountID column is edited
        Me.ListView1.SelectedItems.Clear()
        'Me.ListView1.Items().Selected = True
        For Each il In Me.ListView1.Items   ' look for selected value in column AccountID (of index 0)
            If il.subitem(0) = Me.dgRuns.Rows(e.RowIndex).Cells("AccountID").Value Then  ' when found particular AccountID
                il.focused = True    ' <<<<<<< focus on selected item
                il.selected = True   ' set it as selected 
                ListView1.Focus()    ' <<<<<<< focus on ListView1
                ListView1.Select()   ' <<<<<<< select ListView1
                Exit For             ' ...and exit the loopo
            End If
        Next il
    End If
End Sub

If you wanted a C# solution, you can use some online converter.

Few comments, though:

  1. I would suggest to use at least basic model-view approach, i.e. in form of DataTables.
  2. You could avoid a lot of hassle by using ComboBox instead of ListView if possible, because it simplifies selection when ValueMember and DisplayMember are set and used. Alternatively, if you need to use multi-column visual output, I'd choose another DataGridView. When properly set, looks as simple as ListView, without the odd data model behind.