Vb.net 如何基于字符串数组中的项创建带有文本的新按钮?
我想创建一个新按钮,其中文本显示在另一个窗体上,用于我通过.csv文本文件填充并使用dataviewgrid显示的Vb.net 如何基于字符串数组中的项创建带有文本的新按钮?,vb.net,winforms,Vb.net,Winforms,我想创建一个新按钮,其中文本显示在另一个窗体上,用于我通过.csv文本文件填充并使用dataviewgrid显示的Globals.stringItemsstring数组中的每个项目 以下是我所拥有的: Public Class Globals Public Shared stringItems As String() End Class Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(OpenFileDial
Globals.stringItems
string数组中的每个项目
以下是我所拥有的:
Public Class Globals
Public Shared stringItems As String()
End Class
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(OpenFileDialog1.FileName)
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {", "}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
DataGridView1.Rows.Add(currentRow)
Globals.stringItems = currentRow
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
End If
Public Function AddNewButton() As System.Windows.Forms.Button
Dim button As New System.Windows.Forms.Button()
For Each item As String In Globals.stringItems
Me.Controls.Add(button)
button.Text = ?????????
Next
Return button
End Function
我离你很近吗?我错过了什么?我似乎无法理解这一点。因为
stringItems
被声明为Public Shared
,所以它在所有函数中都是全局访问的。因此,您不需要像Globals.stringItems
那样进行指定。您的AddNewButton()
函数缺少一些逻辑
我从你给的片段中观察到了这些
Public Sub AddNewButton()
Dim button As New System.Windows.Forms.Button()
Dim buttonTop As Integer = 100
For Each item As String In stringItems
Dim Location As New Point(100, (buttonTop + 20))
button.Location = Location
button.Text = item
button.Width=150
Me.Controls.Add(button)
buttonTop += 20
Next
End Function
如果
stringItems
包含7个元素,那么它将创建7个按钮它似乎只为数组中的一个项目生成一个按钮。CSV文件的结构为ITEM1a、ITEM1b,然后在DataViewGrid中以2列显示。我假设代码中的Globals.stringItems=currentRow正在将DataViewGrid的行作为字符串数组项添加到Globals.stringItems的项中。我的想法正确吗?生成的按钮仅为1个按钮,即使有5行,并且只显示ITEM1a作为按钮文本。ok。好的Globals.stringItem
@子文件执行时的值是什么?Globals.stringItems应该包含从CSV文件加载的所有内容(如果我的代码Globals.stringItems=currentRow实际上是在向Globals.stringItems添加值)。它是动态的,因此CSV文件可以有x个条目,这些条目遵循ITEM1a、ITEM1b、ITEM2a、ITEM2b等的结构。这意味着stringItems(0)=“ITEM1a、ITEM1b”stringItems(1)=“ITEM2a、ITEM2b”
在这种情况下,您必须创建4个按钮,不是吗?不。它将创建两个按钮,按钮1和按钮上的文本为“ITEM1a、ITEM1b”按钮2上的“ITEM2a,ITEM2b”。这假设我的代码行Globals.stringItems=currentRow正在将CSV中的项目作为数组中的元素正确添加到stringItems。我不确定该代码行是否正常工作。