我不确定是否可能?需要建议
我想将2个不同文件夹中的文件名显示在2个不同的DataGridview控件中,这些控件位于TabControl1的2个标签页中。这是我尝试过的代码。通过运行此代码,我可以将文件夹中的文件名显示在Tabpage1中的DataGridView1上,但不能显示在tabpage2的DataGridView2中。
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With DataGridView1
.Columns.Add("Column 0", "TaskName")
.AutoResizeColumns()
End With
With DataGridView2
.Columns.Add("Column 0", "TaskName")
.AutoResizeColumns()
End With
Dim rowint As Integer = 0
Dim name As String
Dim directoryInfo As New System.IO.DirectoryInfo("C:\Demo\Sample1")
Dim fileInfo = System.IO.Directory.GetFiles(directoryInfo.ToString)
For Each name In fileInfo
DataGridView1.Rows.Add()
Dim filename As String = System.IO.Path.GetFileName(name)
DataGridView1.Item(0, rowint).Value = filename
rowint = rowint + 1
Next
End Sub
Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.Click
If (TabControl1.SelectedTab.Name.ToString) = "TabPage2" Then
MessageBox.Show(TabControl1.SelectedTab.Name.ToString)
Dim rowint As Integer = 0
Dim name As String
Dim directoryInfo As New System.IO.DirectoryInfo("C:\Demo\Sample2")
Dim fileInfo = System.IO.Directory.GetFiles(directoryInfo.ToString)
For Each name In fileInfo
DataGridView2.Rows.Add()
Dim filename As String = System.IO.Path.GetFileName(name)
DataGridView1.Item(0, rowint).Value = filename
rowint = rowint + 1
Next
End If
End Sub
答案 0 :(得分:-1)
这是您的代码(行号供参考):
1) For Each name In fileInfo
2) DataGridView2.Rows.Add()
3) Dim filename As String = System.IO.Path.GetFileName(name)
4) DataGridView1.Item(0, rowint).Value = filename
5) rowint = rowint + 1
6) Next
您的错误来自第4行,它引用了错误的DataGridView控件。它应该是:
4) DataGridView2.Item(0, rowint).Value = filename
使用您的代码,您需要在每次单击第二个选项卡时清除DataGridView2,否则您的数据网格将开始扩展并添加额外的空行。
不确定在TabControl1 Click事件中使用此代码是否有意义 - 您可能希望将此代码移动到Load事件,就像使用第一个数据网格一样。