使用Checkbox删除GridView中的多行,在网格外删除按钮,无需转到数据库

时间:2016-11-23 20:05:27

标签: asp.net vb.net gridview datatable

如何使用Checkbox,删除网格外部的按钮删除GridView中的多个行,而无需转到数据库?

我的目的是能够通过Gridview中的SelectedCheckbox删除多行。之后,我使用gridview中的数据显示来对数据库进行更改。

Dim dt As DataTable = ViewState("gridview")
Dim row As GridViewRow
For Each row In gridview.Rows
    Dim SelectedRow As CheckBox = CType(row.FindControl("cbSelect"), CheckBox)
    If SelectedRow.Checked Then 

        'gridview.rows(row.index).visible = false is not my case because those indexes are still there

    End If
Next

我无法使用gridview.rows(row.index).remove() / delete()

我的第二个选项是通过viewstate()将gridview存储到datatable。当我尝试在FOR EACH循环中删除索引时,它显示错误,因为在第一次删除数据表reindex之后。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我通过从下往上删除行来完成第二个选项 我真的很感激如果有人能帮我解决我的第一选择。

Dim dt As DataTable = ViewState("gridview")
    For i As Integer = gridview.Rows.Count - 1 To 0 Step -1
        Dim row As GridViewRow = gridview.Rows(i)
        Dim SelectedRow As CheckBox = CType(row.FindControl("cbSelect"), CheckBox)
        If SelectedRow.Checked Then
            dt.Rows(i).Delete()
        End If

    Next
    gridview.DataSource = dt
    gridview.DataBind()

答案 1 :(得分:0)

是的,是的,从下往上删除每一行。我相信会是这样的。

Private Sub Button_Delete_Checked_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button_Delete_Checked.Click
    For Each row As DataGridViewRow In DataGridView1.Rows
        If row.Cells("ToDelete").Value Then
            MessageBox.Show(row.Cells("SomeText").Value & " will be deleted.")

        End If

    Next
End Sub

enter image description here

对于Insert Into,这种方法应该可以正常工作。

Dim Con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Music_Sales_Database.mdb;")
Dim Com As OleDbCommand
Dim SaleCode As Integer
Dim MusicID As String
Dim SubTotalPrice As Decimal
Dim Copies1 As Integer
Dim STR1 As String

SaleCode = 1

Com = New OleDbCommand
Com.Connection = Con
Connection.open()
For x As Integer = 0 To SalesDataGridView.Rows.Count - 1
    MusicID = SalesDataGridView.Rows(x).Cells(0).Value
    SubTotalPrice = SalesDataGridView.Rows(x).Cells(5).Value
    Copies1 = SalesDataGridView.Rows(x).Cells(3).Value
    STR1 = "INSERT INTO Sales(Sales_ID, Sales_Date, Copies, Music_ID, Staff_ID, Total_Price) VALUES (@Sales_ID, @Sales_Date, @Copies, @Music_ID, @Staff_ID, @Total_Price)"
    Dim Comm As New OleDbCommand(STR1, Con)
    Comm.Parameters.AddWithValue("@Sales_ID", SaleCode)
    Comm.Parameters.AddWithValue("@Sales_Date", txtDateAndTime)
    Comm.Parameters.AddWithValue("@Copies", Copies1)
    Comm.Parameters.AddWithValue("@Music_ID", MusicID)
    Comm.Parameters.AddWithValue("@Staff_ID", txtStaff_ID)
    Comm.Parameters.AddWithValue("@Total_Price", SubTotalPrice)
    Command.ExecuteNonQuery()
    Comm.Dispose()
Next
Connection.Close()

显然,您需要修改它以满足您的特定需求。