如何删除动态创建的datagridview vb.net中的行

时间:2016-03-21 22:57:17

标签: vb.net winforms dynamic datagridview vb.net-2010

我试图删除动态创建的DataGridView中的行,我使用此代码但它不起作用(dgv不是...的成员)

datagridviews的创建如下:

If ComboBox1.Text = "Excel" Then
        Static Dim cmd As String
        Using fold As New OpenFileDialog
            fold.Filter = "sheet files (*.xls)|*.xls|All files (*.*)|*.*"
            fold.Title = "Select file"
            If fold.ShowDialog() = Windows.Forms.DialogResult.OK Then
                fold.RestoreDirectory = True
                cmd = fold.FileName
            End If
        End Using
        Try
            Static Dim MyConnection As System.Data.OleDb.OleDbConnection
            Dim Dataset As System.Data.DataSet
            Static Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
            Dim shlist As ArrayList = getExcelSheetsName(cmd)
            MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & cmd & ";Extended Properties=Excel 8.0;")
            For i As Long = 0 To shlist.Count() - 1
                Dim myTabPage As New TabPage()
                Dim dgv As DataGridView = New DataGridView()
                myTabPage.Text = shlist(i) & (TabControl1.TabPages.Count + 1)
                TabControl1.TabPages.Add(myTabPage)
                myTabPage.Controls.Add(dgv)
                dgv.Dock = DockStyle.Fill
                dgv.AutoSizeColumnsModeDataGridViewAutoSizeColumnsMode.Fill
                MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [" & shlist(i) & "$]", MyConnection)
                Dataset = New System.Data.DataSet
                MyCommand.Fill(Dataset)
                dgv.DataSource = Dataset.Tables(0)
                MyConnection.Close()
            Next

        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try

    End If

,删除按钮的代码是:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    For Each row As DataGridViewRow In TabControl1.SelectedTab.datagridview.SelectedRows
        DataGridView.Rows.Remove(row)
    Next
End Sub

任何帮助将不胜感激...谢谢

1 个答案:

答案 0 :(得分:0)

当然,您无法使用TabControl1.SelectedTab.datagridview,因为datagridview不是TabPage的成员,而是您可以使用Controls TabPage集合找到网格Dim grid = DirectCast(Me.TabControl1.SelectedTab.Controls(0), DataGridView) If (grid IsNot Nothing) Then For Each dr As DataGridViewRow In grid.SelectedRows If (Not dr.IsNewRow) Then grid.Rows.Remove(dr) End If Next End If 1}}这样:

start = DateTime.Now;
Console.Write("*Processing variables");
Task entireTask = Task.WhenAll(tasks);
Task progress = new Task(() => { while (!entireTask.IsCompleted) { Console.Write("."); System.Threading.Thread.Sleep(1000); } });
progress.Start();
entireTask.Wait();
timeDiff = DateTime.Now - start;
Console.WriteLine("\n*Operation completed in {0} seconds.", timeDiff.TotalSeconds);