Cycle through xml data in VB.Net - vb.net

I posted a question about how to read the content of external xml files in VB.Net (find it here) and so far everything is going great, but I have no idea how to cycle through the data (they are all elements called savedPassword with a specific id number). Now, I know I am supposed to give a minimum of code, but I am just starting off in XML and VB.Net and I have no idea how much code I need to give for someone to help me out with a script, so here I am, giving a paragraph of code blocks...
I have the following code so far and it works amazingly well (so if no one could modify it, that would be amazing).
My module (Overview.vb):
' Dim values for directories and paths '
Public ReadOnly DirectoryHome As String = "C:\VelocityDK Codes"
Public ReadOnly DirectoryApp As String = "C:\VelocityDK Codes\Password Manager"
Public ReadOnly DataFile As String = "C:\VelocityDK Codes\Password Manager\appData.xml"
' Dim values for .xml file '
Public ReadOnly xmlRoot As String = "savedData"
My [general] form reading the data from my xml file (frmManager.vb):
Option Strict On
Imports System.IO
Imports System.Xml.Serialization
' Some unrelated code '
' This current line is not in the code, but I am disabling the error message with an "unused member" - which is refering to the xmlRoot value right below. '
#Disable Warning IDE0051 ' Remove unused private members
Private ReadOnly xmlRoot As String = "savedData"
#Enable Warning IDE0051 ' Remove unused private members
' Class to represent the xml file '
Public Class SavedData
<XmlElement("savedPassword")>
Public Property SavedPasswords As List(Of SavedPassword)
End Class
' Class to represent data from external xml file '
Public Class SavedPassword
<XmlAttribute("id")>
Public Property ID As Byte
<XmlElement("name")>
Public Property Name As String
<XmlElement("email")>
Public Property Email As String
<XmlElement("password")>
Public Property Password As String
End Class
' Read xml content at first load '
Private Sub FrmManager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filename = DataFile
Dim data As SavedData
Dim serializer As New XmlSerializer(GetType(SavedData))
Using sr = New StreamReader(filename)
data = CType(serializer.Deserialize(sr), SavedData)
End Using
For Each sp In data.SavedPasswords
txtID.Text = {sp.ID}.ToString
txtName.Text = {sp.Name}.ToString
txtEmail.Text = {sp.Email}.ToString
txtPassword.Text = {sp.Password}.ToString
Next
End Sub
Finally, my .xml file (appData.xml located in the directory C:\VelocityDK Codes\Password Manager) looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<savedData>
<savedPassword id="01">
<name>Name 01</name>
<email>email01#mail.com<email>
<password>password01</password>
</savedPassword>
<savedPassword id="02">
<name>Name 02</name>
<email>email02#mail.com<email>
<password>password02</password>
</savedPassword>
<!-- Other sections like the aboves going from id's 03 to 06 -->
<savedPassword id="07">
<name>Name 07</name>
<email>email07#mail.com<email>
<password>password07</password>
</savedPassword>
</savedData>
In brief, I have two buttons (btnPrevious & btnNext) and I want to make it so that when I click on the btnPrevious button, it goes to the previous savedPassword (located in my xml file) and vice versa for the btnNext button. How can I do so?

First of all, make your form's load event look like this.
'Make this global
Dim data As SavedData
Private Sub FrmManager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filename = DataFile
Dim serializer As New XmlSerializer(GetType(SavedData))
Using sr = New StreamReader(filename)
data = CType(serializer.Deserialize(sr), SavedData)
End Using
'Remove for loop to display just the first record. .
txtID.Text = {data.SavedPasswords(0).ID}.ToString
txtName.Text = {data.SavedPasswords(0).Name}.ToString
txtEmail.Text = {data.SavedPasswords(0).Email}.ToString
txtPassword.Text = {data.SavedPasswords(0).Password}.ToString
End Sub
Next, keep an index somewhere in your program for cycling back and forth the list.
Dim data As SavedData
Dim currentIndex As Integer = 0
Next, Under the button click events, add the following code
'Next button
Public Sub BtnNext_Click(sender As Object, e As EventArgs)
If currentIndex < data.SavedPasswords.Count() Then
currentIndex += 1
Else
MessageBox.Show("End of data reached")
End If
txtID.Text = {data.SavedPasswords(currentIndex).ID}.ToString
txtName.Text = {data.SavedPasswords(currentIndex).Name}.ToString
txtEmail.Text = {data.SavedPasswords(currentIndex).Email}.ToString
txtPassword.Text = {data.SavedPasswords(currentIndex) .Password}
End Sub
'Previous button
Public Sub BtnPrevious_Click(sender As Object, e As EventArgs)
If currentIndex > 0 Then
currentIndex -= 1
Else
MessageBox.Show("This is the first record!")
End If
txtID.Text = {data.SavedPasswords(currentIndex).ID}.ToString
txtName.Text = {data.SavedPasswords(currentIndex).Name}.ToString
txtEmail.Text = {data.SavedPasswords(currentIndex).Email}.ToString
txtPassword.Text = {data.SavedPasswords(currentIndex).Password}
End Sub

I would do the following.
First, create some global variable which would keep the current saved password ID. Then the following procedure will search for the next ID. Note that the actual getting XML must be realized by you.
Private curr_id$ = "01" '//Global variable
'// The direction we're searching
Enum Direction
Forward
Backward
End Enum
'// Get the <savedPassword> element. The function returns Nothing,
'// if it doesn't find ID.
Function GetSavedPassword(direction As Direction) As XElement
Dim obj_xml =
<?xml version="1.0" encoding="UTF-8"?>
<savedData>
<savedPassword id="01">
<name>Name 01</name>
<email>email01#mail.com</email>
<password>password01</password>
</savedPassword>
<savedPassword id="02">
<name>Name 02</name>
<email>email02#mail.com</email>
<password>password02</password>
</savedPassword>
<!-- Other sections like the aboves going from id's 03 to 06 -->
<savedPassword id="07">
<name>Name 07</name>
<email>email07#mail.com</email>
<password>password07</password>
</savedPassword>
</savedData>
Dim next_id = -1 '//ID we're searching (initial state)
Dim curr_id_num = CInt(curr_id) '//Convert string to int
'// Get all IDs from XML
Dim ids = obj_xml.<savedData>.<savedPassword>.Select(Function(x) CInt(x.#id))
'// Next we compare the current ID with available IDs
If direction = Direction.Forward Then
'// If we need to go FORWARD,
'// we must get all IDs which are greater than current id
Dim next_ids = ids.Where(Function(id) id > curr_id_num)
'// Make sure we have found something -
'// in this case it's safe to call Min()
If next_ids.Any() Then next_id = next_ids.Min()
ElseIf direction = Direction.Backward
'// If we need to go BACKWARD,
'// we must get all IDs which are less than current id
Dim next_ids = ids.Where(Function(id) id < curr_id_num)
'// Make sure we have found something -
'//in this case it's safe to call Max()
If next_ids.Any() Then next_id = next_ids.Max()
End If
'// If we found id, it will be greater than 0
If next_id > 0 Then
Dim id_string = If(next_id <= 9, "0" & next_id, next_id)
Return obj_xml.<savedData>.<savedPassword>.
Where(Function(p) p.#id = id_string).
FirstOrDefault()
End If
End Function
'// Usage
Sub Main()
Dim saved_password As XElement = GetSavedPassword(Direction.Forward)
If saved_password IsNot Nothing Then
'// Update current id
curr_id = saved_password.#id
Dim name = saved_password.<name>(0)
Dim email = saved_password.<email>(0)
Dim password = saved_password.<password>(0)
'// Update state of the program
'// ....
End If
End Sub

Related

How would you structure data with different datatypes in VB.NET

Right now I have many locations with this structure. At the moment I have: name as string and x,y,z positions as single. So it's a mix of data types and I might want to add both more data in the future and also other data types. I must be able to easily extract any part of this data.
Example of how I'll work with this data is: When I choose South Wales from a combobox then I want to get its properties, x,y,z populated in a textbox. So they need to be "linked". If I choose London then it'll have its x,y,z properties etc.
My initial idea is just to dim every single data such as in the first example below. This should be the easiest way with 100% control of what's what, and I could easily extract any single data but at the same time might get tedious I assume, or am I wrong? Is it a good way to approach this?
Dim SW_FP As String = "South Wales"
Dim SW_FP_X As Single = "489,1154"
Dim SW_FP_Y As Single = "-8836,795"
Dim SW_FP_Z As Single = "109,6124"
The next example below is something i just googled up. Is this a good method?
Dim dt As DataTable = New DataTable
dt.Columns.Add("South Wales", GetType(String))
dt.Columns.Add("489,1154", GetType(Single))
dt.Columns.Add("-8836,795", GetType(Single))
dt.Columns.Add("109,6124", GetType(Single))
OR should I use something else? Arrays, Objects with properties... and this is where my ideas end. Are there other methods? XML?
I want to do it in a smart way from start instead of risking to rewrite/recreate everything in the future. So my main question is: Which method would you suggest to be the smartest to choose? and also if you could provide a super tiny code example.
You mentioned that when you choose an item you want to get it's properties. This shows that you are looking for objects. If not using a database one example could be to make Location objects and have a List of these to be added or removed from. Then you have a lot of different ways to get the data back from the List. For example:
Class:
Public Class Location
Public Property Name As String
Public Property X As Single
Public Property Y As Single
Public Property Z As Single
End Class
List:
Dim locations As New List(Of Location)
Dim location As New Location With {
.Name = "South Wales",
.X = 1.1,
.Y = 1.2,
.Z = 1.3
}
locations.Add(location)
LINQ to get result:
Dim result = locations.SingleOrDefault(Function(i) i.Name = "South Wales")
This is just an example for use within your program, hope it helps.
Disclaimer: Untested code. It's more to guide you than copy-paste into your project.
First, create a Class that will represent the structured data:
Public Class Location
Public Property Name As String
Public Property PositionX As Single
Public Property PositionY As Single
Public Property PositionZ As Single
Public Sub New()
Me.New (String.Empty, 0, 0, 0)
End Sub
Public Sub New(name As String, x As Single, y As Single, z As Single)
Me.Name = name
Me.PositionX = x
Me.PositionY = y
Me.PositionZ = z
End Sub
Now, you can create a List(Of Location) and use that List to bind to a ComboBox, like this:
Dim list As New List(Of Location) = someOtherClass.ReadLocations ' Returns a List(Of Location) from your database, or file, or whatever.
cboLocations.DataSource = list
cboLocations.DisplayMember = "Name" ' The name of the Location class' Property to display.
cboLocations.ValueMember = "Name" ' Use the same Name Property since you have no ID.
You can also forego the list variable declaration like the following, but I wanted to show the declaration of list above:
cboLocations.DataSource = someOtherClass.ReadLocations
Function someOtherClass.ReadLocations() may populate the List(Of Locations) in a way similar to this. Note I'm not including data access code; this is just an example to show how to add Location objects to the List(Of Location):
Dim list As List(Of Location)
' Some loop construct
For each foo in Bar
Dim item As New Location(foo.Name, foo.X, foo.Y, foo.Z)
list.Add(item)
' End loop
Return list
The "magic" happens when you select an option from the ComboBox. I forget the ComboBox event offhand, so that's homework for you :-) You take the selected Object of the ComboBox and cast it back to the native type, in this case Location:
Dim item As Location = DirectCast(cboLocations.SelectedItem, Location)
txtName.Text = item.Name
txtPosX.Text = item.PositionX.ToString
txtPosY.Text = item.PositionY.ToString
txtPosZ.Text = item.PositionZ.ToString
Here is one way, using a DataTable as you mentioned. This is a stand alone example project just to show code used.
This example loads data from file is found and saves data on exit.
Form1 Image
' Stand alone example
' needs DataGridView1, Label1 and
' ComboBox1 on the Designer
' copy/replace this code with default
Option Strict On
Option Explicit On
Public Class Form1
Dim dt As New DataTable("Freddy")
Dim bs As New BindingSource
'edit path/filename to use as test data path
Dim filepath As String = "C:\Users\lesha\Desktop\TestData.xml"
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
dt.WriteXml(filepath)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With dt
dt.Columns.Add("Country", GetType(String))
dt.Columns.Add("x", GetType(String))
dt.Columns.Add("y", GetType(String))
dt.Columns.Add("z", GetType(String))
' add extra column to hold concatenated
' location (could be a hidden column)
dt.Columns.Add("CombLoc", GetType(String), "'x = ' + x + ' y = ' + y + ' z = ' + z")
If IO.File.Exists(filepath) Then
' saved file found so load it
dt.ReadXml(filepath)
Else
' no saved file so make one test row
.Rows.Add("South Wales", 489.1154, -8836.795, 109.6124)
End If
End With
bs.DataSource = dt
DataGridView1.DataSource = bs
' set any properties for DataGridView1
With DataGridView1
' to hide Combined Location column
.Columns("CombLoc").Visible = False
' dontwant row headers
.RowHeadersVisible = False
End With
set up ComboBox
With ComboBox1
.DataSource = bs
' displayed item
.DisplayMember = "Country"
' returned item
.ValueMember = "CombLoc"
If .Items.Count > 0 Then .SelectedIndex = 0
End With
' default Label text
Label1.Text = "No items found"
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
no items in list so exit sub
If ComboBox1.SelectedIndex < 0 Then Exit Sub
send returneditem to Label
Label1.Text = ComboBox1.SelectedValue.ToString
End Sub
End Class

VB.Net Search for text and replace with file content

This is a follow on question to a post I made. Append one file into another file
I need to search the master document for entities "&CH1.sgm" to "&CH33.sgm",
mark where they are in the master document and replace the entity call with the matching file "Chapter1.sgm" found in "fnFiles". I can change the file names and entities to anything if that will help.
My code copies the text of a file and appends it to the bottom of the master_document.sgm. But now I need it to be more intelligent. Search the Master document for entity markers, then replace that entity marker with that file contents match. The file number and entity number match up. e.g.(&CH1; and Bld1_Ch1.sgm)
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
Dim searchDir As String = txtSGMFile.Text 'Input field from form
Dim masterFile = "Bld1_Master_Document.sgm"
Dim existingFileMaster = Path.Combine(searchDir, masterFile)
'Read all lines of the Master Document
Dim strMasterDoc = File.ReadAllText(existingFileMaster) '// add each line as String Array.
'?search strMasterDoc for entities &Ch1.sgm
'?replace entity name "&Ch1.sgm" with content of file "Bld1_Ch1.sgm" this content if found below
'? do I use a book mark? Replace function?
'Get all the sgm files in the directory specified
Dim fndFiles = Directory.GetFiles(searchDir, "*.sgm")
'Set up the regular expression you will make as the condition for the file
Dim rx = New Regex(".*_Ch\d\.sgm")
Dim ch1 = New Regex(".*_Ch[1]\.sgm")
'Use path.combine for concatenatin directory together
'Loop through each file found by the REGEX
For Each fileNo In fndFiles
If rx.IsMatch(fileNo) Then
If ch1.IsMatch(fileNo) Then
Dim result = Path.GetFileName(fileNo)
'Use path.combine for concatenatin directory together
Dim fileToCopy = Path.Combine(searchDir, result)
'This is the file we want to copy into MasterBuild but at specific location.
'match &ch1.sgm inside strMasterDoc
Dim fileContent = File.ReadAllText(fileToCopy)
'Search master file for entity match then append all content of fileContent
File.AppendAllText(existingFileMaster, fileContent)
MessageBox.Show("File Copied")
End If
End If
Next
Close()
End Sub
If I understand correctly (big if), you want to replace the the text of the abbreviated chapter name in the master file with the contents of the file it refers to at the spot where the abbreviation is found.
I made a class to handle the details.
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
'Add a FolderBrowseDialog to your form designer
FolderBrowserDialog1.ShowDialog()
Dim searchDir As String = FolderBrowserDialog1.SelectedPath
Dim existingFileMaster = Path.Combine(searchDir, "Bld1_Master_Document.sgm")
Dim lstFileChanges = CreateList(searchDir)
'The following method does NOT return an array of lines
Dim strMasterDoc = File.ReadAllText(existingFileMaster)
For Each fc In lstFileChanges
strMasterDoc = strMasterDoc.Replace(fc.OldString, fc.NewString)
Next
File.WriteAllText(existingFileMaster, strMasterDoc)
End Sub
Private Function CreateList(selectedPath As String) As List(Of FileChanges)
Dim lstFC As New List(Of FileChanges)
For i = 1 To lstFC.Count
Dim fc As New FileChanges
fc.OldString = $"&CH{i}.sgm"
fc.FileName = $"Chapter{i}.sgm"
fc.NewString = File.ReadAllText(Path.Combine(selectedPath, fc.FileName))
lstFC.Add(fc)
Next
Return lstFC
End Function
Public Class FileChanges
Public Property OldString As String '&CH1.sgm
Public Property FileName As String 'Chapter1.sgm
Public Property NewString As String 'Contents of Chapter1.sgm, the string to insert
End Class
Testing .Replace
Dim s As String = "The quick brown fox jumped over the lazy dogs."
s = s.Replace("fox", "foxes")
MessageBox.Show(s)

Visual Basic rename a group of files

I'm starting with Visual Basic and use Visual Studio 2012 and trying to make a tool for renaming a group of files.
How it shoul be:
1- With the "Select Files" button, I can choose the files and they are listed in the ListBox
2- "Old value" is a textbox and is the value to be changed in the filename. For example: fff
3- "New value" is a textbox and is the new value that should replace the old. For example: zzz
4- Rename is a button to start the process.
To rename only one file it's not a problem.
But how to rename all the files from the ListBox which are containing the Oldvalue ?
Can you please help me!
Thanks
I suggest looping over the selected files in the listbox, checking to see which ones contain the OldValue string.
You could use string.contains http://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
Sounds like you have the replace function sorted since you say it's no problem to do just one file.
Thank you 70Mike.
But I have some problem with the loop.
If it works only for 1 file and not for all.
Here is my code:
Public Class frmRename
Private Sub cmdSelectFile_Click(sender As Object, e As EventArgs) Handles cmdSelectFile.Click
If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
For Each S As String In OpenFileDialog1.FileNames
lstSelectFiles.Items.Add(S)
Next
Else : Exit Sub
End If
End Sub
Private Sub cmdRename_Click(sender As Object, e As EventArgs) Handles cmdRename.Click
Try
For LC As Integer = 0 To lstSelectFiles.Items.Count - 1
Dim s1 As String = lstSelectFiles.Items(LC)
Dim s2 As String = txtbOld.Text
Dim b As String
b = s1.Contains(s2)
Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b)
Do While b = True
Dim oldFile As String = lstSelectFiles.Items(LC)
Dim newFile As String = Replace(lstSelectFiles.Items(LC), txtbOld.Text, txtbNew.Text)
If File.Exists(oldFile) And Not File.Exists(newFile) Then
File.Move(oldFile, newFile)
Kill(oldFile)
End If
Loop
Next
Catch ex As Exception
MsgBox("No file renamed")
End Try
End Sub
End Class

check for uniqueness of employee id number

Cant seem to figure out how to check for a unique Employee id Number. I know the validation has to go in the form load, just not sure how to go about it.
Public Class Form1
Dim filename As String
Dim dataFile As System.IO.File
Dim dataWrite As System.IO.StreamWriter
''LOADING AND WRITE TO TEXT DOCUMENT
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'asks user for file name
filename = InputBox("Enter output file name")
If IO.File.Exists(filename) Then
dataWrite = IO.File.AppendText(filename)
Else
MessageBox.Show("filename does not exist")
filename = InputBox("Enter output file name")
dataWrite = IO.File.CreateText(filename)
End If
cboDepart.Items.Add("Accounting")
cboDepart.Items.Add("Administration")
cboDepart.Items.Add("Marketing")
cboDepart.Items.Add("MIS")
cboDepart.Items.Add("Sales")
End Sub
'------
Public EMPLOYEEIDS As String
Dim employeeID1 As ServerData()
Dim employeeID2 As ServerData()
Dim reader As String = My.Computer.FileSystem.ReadAllText("servers.lst")
Dim s() As String
Dim Totalemployeeids As String = CStr(reader.Length)
Dim x As Integer = 0
Dim myArray As String() = reader.Split("|"c)
For x = 1 To Totalemployeeids
employeeID1(x).ServerName = myArray(0)
employeeID2(x).IDname = myarray(0)
Form1_load.ListBox1.Items.Add(Servers(x).ServerName)
x += 1
Next
Structure ServerData
End Structure
End Class
You usually do not insert a unique ID from the client side. Instead, it is inserted automatically by the database server. There is a way to retrieve an inserted ID back, if you need it for display (can also act as a confirmation that a record was successfully inserted):
SELECT SCOPE_IDENTITY()
An example is shown in this answer:
How to get last inserted id? (C#)
On the client side, you need to implement insertion of everything but the ID, in this case you don't need to check for uniqueness. There may be other validation issues upon commit though (unique key violation, data type mismatch) - make sure you catch exceptions and display them to the user as appropriate.

Referencing an Unbound DataGridView Without Specifically Naming It?

I am using 3 unbound DataGridView controls to display certain information. To load the information into those DGVs, I am pulling the information from an encrypted file, decrypting it, parsing the information, then trying to fill the DGVs with that information. The loading from the file is called by the menu item click. Here is what I have so far:
Private Sub miCLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles miCLoad.Click
Dim FilePath As String = "C:\FList\CList.clt"
Dim LoadFile As New SaveandLoad.SaveAndLoad
Dim FileRead As New Simple3Des("MyPassword")
Dim FileString As String = FileRead.ReadFile(FilePath)
With LoadFile
.WhichList = dgCourses
.FilePath = FilePath
.DecryptedString = FileRead.DecryptData(FileString)
.dgList = dgCourses
End With
Call LoadFile.LoadFile()
End Sub
Public Class SaveandLoad
Public Property WhichList As New DataGridView
Public Property FilePath As String
Public Property DecryptedString As String
Public Property EncryptedString As String
Public Property dgList As Control
Public Sub LoadFile()
Dim dgRow As DataGridViewRow
Dim dgCell As DataGridViewTextBoxCell
Dim Lines() As String = DecryptedString.Split(vbLf)
Dim LinesList As List(Of String) = Lines.ToList
LinesList.RemoveAt(Lines.Length - 1)
For Each Line As String In LinesList
Dim Fields() As String = Line.Split(",")
dgRow = New DataGridViewRow
For x = 0 To (WhichList.Columns.Count - 1) Step 1
dgCell = New DataGridViewTextBoxCell
dgCell.Value = Fields(x).ToString
dgRow.Cells.Add(dgCell)
Next
WhichList.Rows.Add(dgRow)
Next
Select Case WhichList.Name
Case "dgCourses"
frmFacultyList.dgCourses = WhichList
frmFacultyList.dgCourses.Refresh()
WhichList.Dispose()
Case "dgFList"
frmFacultyList.dgFList = WhichList
frmFacultyList.dgFList.Refresh()
WhichList.Dispose()
Case "dgSList"
frmFacultyList.dgSList = WhichList
frmFacultyList.dgSList.Refresh()
WhichList.Dispose()
End Select
MsgBox("List Successfully Loaded", vbOKOnly, "Load")
End Sub
I want to be able to reference (or fill) a DGV without using 'select case' or 'if-then' statements. This will be too inefficient once I start adding the many other DGVs, that will be added in the future. Therefore, the title is the main question. I am using VS Express 2010.
I don't know VB too much, however, I'll post my solution in C# (may be helpfull in some way....)
DataGridView myDGV;
foreach (var item in this.Controls)
{
if (item.GetType() == typeof(DataGridView))
{
if (((DataGridView)item).Name == WhichList.Name)
{
//Cannot assing to 'item' here, because it is a 'foreach iteration variable'
//However you can save the variable for later use.
myDGV = (DataGridView)item;
}
}
}
myDGV = WhichList;
// different approach
DataGridView myDGV = (DataGridView)this.Controls.Find(WhichList.Name, false).First();
myDGV = WhichList;
Here is what worked for me in VB.NET:
Dim FormControls As New frmFacultyList.ControlCollection(frmFacultyList)
For Each DGV As DataGridView In FormControls
If WhichList.Name = DGV.Name Then
DGV = WhichList
DGV.Refresh()
End If
Next
Make an instance of the control collection then search specifically for DGVs using For Each. Simple and efficient.