Results 1 to 8 of 8

Thread: [RESOLVED] DataGridView: Can we find a cell by its first column?

  1. #1

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    381

    Resolved [RESOLVED] DataGridView: Can we find a cell by its first column?

    First of all is there any DGV snippet or its examples in codebank? I'd be grateful if you redirect me there.

    Consider you have a long list of string matrix (No datasets and no dbs, just manual CSV written values) and you want to find/locate/search a specific row while "sort" is open for user to manipulate the entire table. But once you want to change a cell value formerly you did this:
    Code:
    DataGridView1.Item(VCol, VRow).Value = (TrackBar1.Value).ToString
    But since user reordered the table cells (not as sorted as I did before) How can we find first column (ID of then entire row) then tell it to change row number VRow?

    1) I was thinking about a for loop to start from the beginning of the table to its end to find exact ID we are looking for (Something like .FindStringExact in ListBox) then updating its cells. But come on... This is Visual Studio, it should be a proper (and in most cases an easier) way to do that, Aye?
    2) Is there a "filter" kind of search (Like a built-in one in DevExpress GridControl but this is a very different complex control and in my opinion ≠DGV) to fine a specific line? (Not by removing/hiding other lines but to automatically scroll horizontally to find a line) some sort of "Go To Line" function?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,689

    Re: DataGridView: Can we find a cell by its first column?

    The fact that you're not using a database doesn't mean that you can't use a DataTable and a BindingSource.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    381

    Re: DataGridView: Can we find a cell by its first column?

    What do you mean?
    In all tutorial videos they all connect it to an access file online on the network, username and password required, after model creating wizard... (This user is taking shelter in his comfort zone, please take him out with making the story look safe)

  4. #4
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,262

    Re: DataGridView: Can we find a cell by its first column?

    Lots of examples, more than one way to do it, just Google "visual basic create datatable from csv file"

  5. #5
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,669

    Re: DataGridView: Can we find a cell by its first column?

    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  6. #6
    Hyperactive Member
    Join Date
    Jul 2022
    Posts
    377

    Re: DataGridView: Can we find a cell by its first column?

    How do you want to have the user edit the cell? Will the edit then be written to the source CSV file? If so, the fact that they sorted the column doesn't affect the ID of the row (does your CSV have a unique ID per row?)

    I downloaded the 100-record organization csv file from here https://www.datablist.com/learn/csv/...mple-csv-files. I filled the grid with the file data, the grid allows for editing, when the user finishes editing it writes the new value to a temp file that is then renamed as the source file.

    I'm sure there is a better way to go about this, but ...
    Code:
       Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
    
            Dim TextFieldParser1 As New TextFieldParser("F:\temp\organizations-100.txt")
    
            TextFieldParser1.Delimiters = New String() {","}
    
            While Not TextFieldParser1.EndOfData
                Dim Row1 As String() = TextFieldParser1.ReadFields()
    
                If dgvData.Columns.Count = 0 Then
                    Dim i As Integer
    
                    For i = 0 To Row1.Count - 1
                        dgvData.Columns.Add(Row1(i), Row1(i))
                    Next
                Else
                    dgvData.Rows.Add(Row1)
                End If
    
            End While
    
            TextFieldParser1.Close()
    
        End Sub
    
        Dim prevCellContents As String
    
        Private Sub dgvData_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles dgvData.CellBeginEdit
            ' save what the data in the cell was before the attempted it
            prevCellContents = dgvData.CurrentCell.Value
        End Sub
    
        Private Sub dgvData_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgvData.CellEndEdit
    
            Dim currentCellContents As String = dgvData.CurrentCell.Value
            Dim rowID As String
            Dim changedFieldIndex As Int16
    
            If currentCellContents <> prevCellContents Then
                ' the cell changed
                rowID = dgvData.Item(0, dgvData.CurrentCell.RowIndex).Value
                changedFieldIndex = dgvData.CurrentCell.ColumnIndex
    
                If UpdateCSVFile(rowID, changedFieldIndex, currentCellContents) Then
                    MsgBox($"You changed the value from {prevCellContents} to {currentCellContents}")
                Else
                    ' the save failed, put the old value back in the cell
                    dgvData.CurrentCell.Value = prevCellContents
                End If
            Else
                MsgBox("Edit has been cancelled")
            End If
    
        End Sub
    
        Private Function UpdateCSVFile(recID As String, columnNumber As Int16, newValue As String) As Boolean
    
            Try
                Dim rwNumber As Long = 0
                Dim parser As New TextFieldParser("F:\temp\organizations-100.txt")   ' open the source file
                parser. Delimiters = New String() {","}
    
                Dim tempFile As New StreamWriter("F:\temp\temp.txt")   ' create a temp file
                Dim tempFileFields As New List(Of String)
                Dim foundID As Boolean
    
                While Not parser.EndOfData
                    Dim fields As String() = parser.ReadFields()
    
                    ' if the record id matches, replace the value - we know the id field is in the first field
                    foundID = fields(0) = recID
                    Dim fld As String
                    For i = 0 To fields.Count - 1
                        fld = fields(i)
                        If fld.IndexOf(",") > 0 Then
                            ' the field itself contains a comma, it must be surrounded by """" to write correctly
                            ' with streamwriter
                            If foundID And i = columnNumber Then
                                ' this is the line that has the edit field value
                                fld = """" & newValue & """"
                            Else
                                fld = """" & fld & """"
                            End If
                        Else
                            If foundID And i = columnNumber Then
                                fld = newValue
                            End If
                        End If
                        tempFileFields.Add(fld)
                    Next
    
                    tempFile.WriteLine(String.Join(",", tempFileFields))   ' write the line of data to the temp file
                    tempFileFields.Clear()
                End While
    
                parser. Close()
                tempFile.Close()
    
                ' rename the old file as a backup with date time stamp
                ' rename the temp file as the file name
                Dim dateTimeStr As String = Format(Now, "MMddyyHmmss")
                My.Computer.FileSystem.RenameFile("F:\temp\organizations-100.txt", $"organizations-100-{dateTimeStr}.txt")
                My.Computer.FileSystem.RenameFile("F:\temp\temp.txt", "organizations-100.txt")
    
                Return True
            Catch ex As Exception
                MsgBox($"Save failed. {ex.Message}")
                Return False
            End Try
    
        End Function
    this is a play around form, ignore the date control. The file is loaded: https://imgur.com/42B84eJ, I sorted by the "Founded" field and entered edit mode (press f2 or dbl click the cell) https://imgur.com/NfWBxed, I changed the year and pressed enter. https://imgur.com/k0xb2gf - it renames the old file (to create a backup) and renames the temp file to the original file name https://imgur.com/qfq5954, the new file after the edit https://imgur.com/4WfsNNi, the original file saved as a backup https://imgur.com/M1s9r7L

    The key is you need well, a key for each record in the CSV file.

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,689

    Re: DataGridView: Can we find a cell by its first column?

    Quote Originally Posted by pourkascheff View Post
    What do you mean?
    I mean that you can still use a DataTable even if you're not using a database. DataTables are often used with databases because they are basically made to behave like an in-memory database table but they are just a thing that contains data so that data can come from anywhere you want it to.
    Quote Originally Posted by pourkascheff View Post
    In all tutorial videos...
    Maybe you should start thinking for yourself a bit instead of just painting by numbers. If you can add a new row to a DataTable in order to save it to a database, why can't you add multiple new rows to a DataTable for other purposes?
    Last edited by jmcilhinney; Jun 6th, 2023 at 04:05 AM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  8. #8

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    381

    Re: DataGridView: Can we find a cell by its first column?

    Thanks all for contribution...

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width