Working in combination of TabControl and DataGridView Control
I am not sure whether it is possible or not? need suggestion
I want to display filenames from 2 different folders into 2 different DataGridview controls that are placed in 2 tab pages of TabControl1. Here is the code that I have tried. By running this code, I can able to show the filenames from a folder onto DataGridView1 in Tabpage1 but not in DataGridView2 of tabpage2.
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
En开发者_StackOverflowd If
End Sub
Here is your code (line numbers for reference):
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
Your error is coming from line 4, which is referencing the incorrect DataGridView control. It should be:
4) DataGridView2.Item(0, rowint).Value = filename
With your code, you need to clear out the DataGridView2 every time you click on your second tab or else your data grid starts to expand with extra empty rows.
Not sure it makes sense to have this code in the TabControl1 Click event-- you might want to move this code to your Load event like you are doing with the first data grid.
精彩评论