-
Jun 5th, 2023, 09:34 AM
#1
Thread Starter
Hyperactive Member
[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?
-
Jun 5th, 2023, 10:53 AM
#2
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.
-
Jun 5th, 2023, 11:55 AM
#3
Thread Starter
Hyperactive Member
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)
-
Jun 5th, 2023, 12:53 PM
#4
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"
-
Jun 5th, 2023, 01:01 PM
#5
Re: DataGridView: Can we find a cell by its first column?
-
Jun 5th, 2023, 02:24 PM
#6
Hyperactive Member
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.
-
Jun 5th, 2023, 08:34 PM
#7
Re: DataGridView: Can we find a cell by its first column?
Originally Posted by pourkascheff
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.
Originally Posted by pourkascheff
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.
-
Jun 6th, 2023, 03:28 AM
#8
Thread Starter
Hyperactive Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|