ASP.NET从gridview删除特定的行

时间:2018-06-29 01:49:13

标签: asp.net database vb.net checkbox

我需要以下问题的帮助。 我尝试从gridview删除特定的行。 下面的代码效果很好,但是在页面加载时显示数据库中的所有数据。 如何过滤数据?我的意思是页面加载时什么也没显示,但是在文本框中输入一些文本后,它会显示带有该文本的行,并且可以通过选中复选框和按钮从文本框中删除其中的一些行。

这是我的代码。请帮助我。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If IsPostBack Then
        GetData()
    End If
    BindGrid()
End Sub

Private Sub BindGrid()
    Dim constr As String = ConfigurationManager _
                .ConnectionStrings("conString").ConnectionString()
    Dim query As String = "select * from TestCustomers"
    Dim con As New SqlConnection(constr)
    Dim sda As New SqlDataAdapter(query, con)
    Dim dt As New DataTable()
    sda.Fill(dt)
    gvAll.DataSource = dt
    gvAll.DataBind()
End Sub

Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    gvAll.PageIndex = e.NewPageIndex
    gvAll.DataBind()
    SetData()
End Sub

Private Sub GetData()
    Dim arr As ArrayList
    If ViewState("SelectedRecords") IsNot Nothing Then
        arr = DirectCast(ViewState("SelectedRecords"), ArrayList)
    Else
        arr = New ArrayList()
    End If
    Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
                .Cells(0).FindControl("chkAll"), CheckBox)
    For i As Integer = 0 To gvAll.Rows.Count - 1
        If chkAll.Checked Then
            If Not arr.Contains(gvAll.DataKeys(i).Value) Then
                arr.Add(gvAll.DataKeys(i).Value)
            End If
        Else
            Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
                                        .FindControl("chk"), CheckBox)
            If chk.Checked Then
                If Not arr.Contains(gvAll.DataKeys(i).Value) Then
                    arr.Add(gvAll.DataKeys(i).Value)
                End If
            Else
                If arr.Contains(gvAll.DataKeys(i).Value) Then
                    arr.Remove(gvAll.DataKeys(i).Value)
                End If
            End If
        End If
    Next
    ViewState("SelectedRecords") = arr
End Sub

Private Sub SetData()
    Dim currentCount As Integer = 0
    Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
                    .Cells(0).FindControl("chkAll"), CheckBox)
    chkAll.Checked = True
    Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
                                    , ArrayList)
    For i As Integer = 0 To gvAll.Rows.Count - 1
        Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
                                        .FindControl("chk"), CheckBox)
        If chk IsNot Nothing Then
            chk.Checked = arr.Contains(gvAll.DataKeys(i).Value)
            If Not chk.Checked Then
                chkAll.Checked = False
            Else
                currentCount += 1
            End If
        End If
    Next
    hfCount.Value = (arr.Count - currentCount).ToString()
End Sub

Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim count As Integer = 0
    SetData()
    gvAll.AllowPaging = False
    gvAll.DataBind()
    Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
                                , ArrayList)
    count = arr.Count
    For i As Integer = 0 To gvAll.Rows.Count - 1
        If arr.Contains(gvAll.DataKeys(i).Value) Then
            DeleteRecord(gvAll.DataKeys(i).Value.ToString())
            arr.Remove(gvAll.DataKeys(i).Value)
        End If
    Next
    ViewState("SelectedRecords") = arr
    hfCount.Value = "0"
    gvAll.AllowPaging = True
    BindGrid()
    ShowMessage(count)
End Sub

Private Sub DeleteRecord(ByVal CustomerID As String)
    Dim constr As String = ConfigurationManager _
                    .ConnectionStrings("conString").ConnectionString
    Dim query As String = "delete from TestCustomers where" & _
                            " CustomerID=@CustomerID"
    Dim con As New SqlConnection(constr)
    Dim cmd As New SqlCommand(query, con)
    cmd.Parameters.AddWithValue("@CustomerID", CustomerID)
    con.Open()
    cmd.ExecuteNonQuery()
    con.Close()
End Sub

Private Sub ShowMessage(ByVal count As Integer)
    Dim sb As New StringBuilder()
    sb.Append("<script type = 'text/javascript'>")
    sb.Append("alert('")
    sb.Append(count.ToString())
    sb.Append(" records deleted.');")
    sb.Append("</script>")
    ClientScript.RegisterStartupScript(Me.GetType(), _
                    "script", sb.ToString())
End Sub

<asp:GridView ID="gvAll" runat="server" 
    AutoGenerateColumns = "false" Font-Names = "Arial" 
    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"  
    HeaderStyle-BackColor = "green" AllowPaging ="true"   
    OnPageIndexChanging = "OnPaging" DataKeyNames = "CustomerID"
    PageSize = "10" >
   <Columns>
    <asp:TemplateField>
        <HeaderTemplate>
            <asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);" />
        </HeaderTemplate> 
        <ItemTemplate>
            <asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"/>
        </ItemTemplate>
    </asp:TemplateField> 
    <asp:BoundField ItemStyle-Width = "150px" DataField = "ContactName" HeaderText = "Contact Name"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "Country" HeaderText = "Country"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "City" HeaderText = "City"/>
   </Columns> 
   <AlternatingRowStyle BackColor="#C2D69B"  />
</asp:GridView> 
    <asp:HiddenField ID="hfCount" runat="server" Value = "0" />
    <asp:Button ID="btnDelete" runat="server" Text="Delete Checked Records" OnClientClick = "return ConfirmDelete();" OnClick="btnDelete_Click" />

2 个答案:

答案 0 :(得分:0)

即使您的问题不清楚,我也会回答我所理解的。

您要在页面加载时显示所有数据,而在回发时要显示选定的行,对吗?

如果是

尝试此代码   如果IsPostBack然后         GetData()     如果结束

其他     BindGrid()

如果这还不能回答您的问题,请告诉我您到底想做什么。

答案 1 :(得分:0)

这将删除所有已选择的行。

For Each row As DataGridViewRow In yourDGV.SelectedRows
    yourDGV.Rows.Remove(row)
Next


Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndelete.Click
  If DataGridView1.SelectedRows.Count > 0 Then
   DataGridView1.Rows.RemoveAt(DataGridView1.CurrentRow.Index)
  Else
   MessageBox.Show("You must select a row")
  End If
End Sub

使用它可能对您有帮助

Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
    For Each gvrow As GridViewRow In gvDetails.Rows
        'Finiding checkbox control in gridview for particular row
        Dim chkdelete As CheckBox = DirectCast(gvrow.FindControl("chkSelect"), CheckBox)
        'Condition to check checkbox selected or not
        If chkdelete.Checked Then
            'Getting UserId of particular row using datakey value
            Dim usrid As Integer = Convert.ToInt32(gvDetails.DataKeys(gvrow.RowIndex).Value)
            Using con As New SqlConnection("YOUR SQL DATABASE CONNECTION")
                con.Open()
                Dim cmd As New SqlCommand("delete from UserDetails where UserId=" & usrid, con)
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End If
    Next
    BindUserDetails()
End Sub