How to read controller properties, automatically added to a table assigned to a DataGridView?
Dim dt As DataTable = New DataTable
dt.Columns.Add("Name")
dt.Columns.Add("Type")
Dim n As Integer = Me.Controls.Count
For i As Integer = 0 To n - 1
dt.Rows.Add(Me.Controls(i).Name.ToString, Me.Controls(i).GetType.ToString)
Next
DataGridView1.DataSource = dt
The above is the check for controls in the Form, it only displays Name
and type
of GroupBoxes, help me use recursive function to check the controls in GroupBox.
Below is my idea, but it was not working:
Public Sub V_gr(ByVal _Obj As Object)
dt.Columns.Add("Name")
dt.Columns.Add("Type")
If (_Obj.Controls.count > 0) Then
Dim i As Integer = _Obj.Controls.count - 1
dt.Rows.Add(_Obj.Controls(i).Name.ToString, _Obj.Controls(i).GetType.ToString)
DataGridView1.DataSource = dt
End If
End Sub
Use a temporary table assigned to DataGridView and display the control information checked on it with 2 columns Name
and Type
You can split the DataTable creation and the Controls enumeration in two different methods:
You could also modify the private method to return a List of objects that can be transformed to a DataTable after.
I've added a Column, named "Parent"
, which references the Parent of the control. It may be useful to know which are the Parents of these Controls.
' Find all Controls in the current Form
DataGridView1.DataSource = ControlsListToDataTable(Me)
Private Function ControlsListToDataTable(parent As Control) As DataTable
If (parent Is Nothing) OrElse (Not parent.HasChildren) Then Return Nothing
Dim dt As DataTable = New DataTable("ParentControls")
dt.Columns.AddRange({
New DataColumn() With {.ColumnName = "Name", .DataType = GetType(String)},
New DataColumn() With {.ColumnName = "Type", .DataType = GetType(String)},
New DataColumn() With {.ColumnName = "Parent", .DataType = GetType(String)}
})
GetAllControls(parent, dt)
Return dt
End Function
Private Sub GetAllControls(parent As Control, dt As DataTable)
For Each ctl As Control In parent.Controls.OfType(Of Control)
dt.Rows.Add({ctl.Name, ctl.GetType().FullName, ctl.Parent.Name})
If ctl.HasChildren Then GetAllControls(ctl, dt)
Next
End Sub
To find a Control in the DataTable, you can use the DataTable.DefaultView Sort and FindRows methods:
[DataTable].DefaultView.Sort = "Name"
Dim result = [DataTable].DefaultView.FindRows("TextBox1")
Or use a LINQ method:
Dim control = [DataTable].Rows.OfType(Of DataRow)().
FirstOrDefault(Function(dr) dr(0).ToString().Equals("TextBox1"))
Where [DataTable]
can be the original DataTable returned by the public method or the DataGridView.DataSource
:
Dim dt = CType(DataGridView1.DataSource, DataTable)
Dim control = dt.Rows.OfType(Of DataRow)(). (... etc ...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.