Использование флажка для удаления строки в Gridview с кодом Visual Basic.net и сохраненными процедурами - PullRequest
0 голосов
/ 13 августа 2010

Инструменты для моего сайта:

  • Visual Studio 2010
  • SQL Management Studio
  • asp.net
  • visual basic.net

Я использую GridView.Из-за кода поиска я не могу использовать функцию автоматического удаления, которую предлагает GridView.

Я нажал на GridView, сказал «Добавить новый столбец» и добавил столбец флажка.

Я хочу иметь возможность установить один или несколько флажков и выбрать кнопку, которая удалит эти строки из базы данных с помощью хранимой процедуры.

Ниже часть ASP.net моего кода

Default.aspx

<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ContactList._Default" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<%-- CONNECTION STRING--%>
            <%--string Connection = "server=Local; uid=sa; pwd=; database=TGMInfo; Connect Timeout=10000";--%>


        <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

            <link href="Styles/Site.css" rel="stylesheet" type="text/css" />

        </asp:Content>
        <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
            <h2>
                Welcome to THE TGM CONTACTS SITE</h2>
            <p>
                &nbsp;</p>


            <p></p>
               <center>
                   <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">


              </asp:ToolkitScriptManager>
               Add a new record to the database<br />
                <br />



        <%--Text boxes for First Name, Last Name and Main Phone Number--%>

            <asp:Label ID="lblFirstName" runat="server" Text="First Name:"></asp:Label>
    &nbsp;<asp:TextBox ID="txtFirstName" runat="server" Width="160px"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;
            <asp:Label ID="LblLastName" runat="server" Text="Last Name:"></asp:Label>
    &nbsp;<asp:TextBox ID="txtLastName" runat="server" Width="160px"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;
            <asp:Label ID="lblMainPhone" runat="server" Text="Main Phone #:"></asp:Label>
    &nbsp;<asp:TextBox ID="txtMainPhone" runat="server" Width="160px"></asp:TextBox>
                <asp:MaskedEditExtender ID="txtMainPhone_MaskedEditExtender" runat="server" 
                   ErrorTooltipEnabled="True" Mask="(999) 999-9999" MaskType="Number" 
                   TargetControlID="txtMainPhone">
               </asp:MaskedEditExtender>
                <br />
            <br />


          <%--Button adds information from the text fields to the SQL Database--%>
               <asp:Button ID="btnAdd" runat="server" Text="Add Record" />
               <br />
               <br />
               <br />
               Search by Last Name<br />
               <asp:Label ID="lblQuery" runat="server" Text="Last Name:"></asp:Label>
    &nbsp;<asp:TextBox ID="txtQuery" runat="server" ToolTip="Search by last name"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
               <br />
               <br />
               <asp:Button ID="BtnQuery" runat="server" Text="Search" />
               <br />
             </center>



        <p>
            &nbsp;</p>
        <p>
            &nbsp;</p>
          <center>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                DataKeyNames="EmpId" 
                EmptyDataText="There are no data records to display." CellPadding="4" 
            ForeColor="#333333" GridLines="None" Height="136px" Width="299px">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
    <%--                <asp:BoundField DataField="MainPhoneNumber" HeaderText="Main Phone Number" 
                        SortExpression="MainPhoneNumber" />--%>
                    <asp:BoundField DataField="EmpId" HeaderText="EmpId" ReadOnly="True" 
                        SortExpression="EmpId" Visible="False" />
                    <asp:BoundField DataField="FirstName" HeaderText="First Name" 
                        SortExpression="FirstName" />
                    <asp:BoundField DataField="LastName" HeaderText="Last Name" 
                        SortExpression="LastName" />
                        <asp:TemplateField HeaderText="Main Phone Number"> 
                    <ItemTemplate> 
                     <asp:Literal ID="litPhone"  runat="server" Text='<%# string.Format("{0:(###) ###-####}", Int64.Parse(Eval("MainPhoneNumber").ToString())) %>' /> 
                    </ItemTemplate> 
                    </asp:TemplateField> 

                    <asp:TemplateField HeaderText="Check For Deletion">
                        <ItemTemplate>
                            <asp:CheckBox ID="CheckBox1" runat="server" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:CheckBox ID="CheckBox1" runat="server" />
                        </EditItemTemplate>
                    </asp:TemplateField>

                </Columns>
                <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                <SortedAscendingCellStyle BackColor="#FDF5AC" />
                <SortedAscendingHeaderStyle BackColor="#4D0000" />
                <SortedDescendingCellStyle BackColor="#FCF6C0" />
                <SortedDescendingHeaderStyle BackColor="#820000" />
            </asp:GridView>
    <p>
         <center>
          <asp:Button ID="Button1" runat="server" Text="Delete Selected Rows" 
              ToolTip="Check desired rows and click this button for deletion" />
              </p>
              <p>
                  &nbsp;</p>
            </center>
        </asp:Content>

Я думаю, что опубликовал все, что мне нужно, если нет, я могу опубликовать больше.Я не опубликовал код-позади (visual basic.net) или 2 хранимые процедуры, которые у меня есть.Я очень новичок в vb.net/asp.net/stored процедурах.

Ответы [ 2 ]

1 голос
/ 19 августа 2010

Используйте этот код для метода удаления, чтобы отсканировать свои флажки и удалить строки.

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    For Each gvr As GridViewRow In GridView1.Rows
        If gvr.Visible AndAlso DirectCast(gvr.FindControl("CheckBox1"), CheckBox).Checked Then
            Response.Write(String.Format("DELETING ROW {0}<br>", gvr.DataItemIndex))
            gvr.Visible = False 'Hide the row without the need for a re-bind'

            'Use the "DataItemIndex" to get the database row key information for your delete'
            'run your delete procedure'
        End If
    Next
End Sub
0 голосов
/ 23 августа 2010

Вот моя информация для поиска отмеченных флажков.

Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As EventArgs) Handles btnDelete.Click


    'Create String Collection to store 
    'IDs of records to be deleted 

    Dim idCollection As New StringCollection()
    Dim strID As String = String.Empty


    'Loop through GridView rows to find checked rows 
    For d = 0 To GridView1.Rows.Count - 1


        If GridView1.Rows(d).Cells.FromKey("DeleteRecord").Value = True Then
            strID = GridView1.Rows(d).Cells.FromKey("EmpID").Value
            idCollection.Add(strID)
        End If
    Next

    'Call the method to Delete records 
    DeleteMultipleRecords(idCollection)


    QueryEmployees("")




End Sub

Вот код для подпрограммы, которая вызывает мою хранимую процедуру.

Private Sub DeleteMultipleRecords(ByVal idCollection As StringCollection)

        Dim SqlConn4 As SqlConnection = New SqlConnection("Password=;Persist Security Info=True;User ID=;Initial Catalog=;Data Source=.\SQLEXPRESS")
        Dim cmd4 As New SqlCommand("Password=;Persist Security Info=True;User ID=;Initial Catalog=;Data Source=.\SQLEXPRESS")
        Dim IDs As String = ""

        For Each id As String In idCollection
            IDs += id.ToString() & ","
        Next


        Try
            'Dim strIDs As String = IDs.Substring(0, IDs.LastIndexOf(","))
            'Dim strSql As String = "Delete from Details  WHERE ID in (" & strIDs & ")"
            For i = 0 To idCollection.Count - 1

                cmd4.CommandType = CommandType.StoredProcedure
                cmd4.Parameters.AddWithValue("@IDs", CInt(idCollection(i)))
                cmd4.CommandText = "dbo.SPDeleteEmp"
                cmd4.Connection = SqlConn4
                SqlConn4.Open()
                cmd4.ExecuteNonQuery()
            Next
        Catch ex As SqlException

            Dim errorMsg As String = "Error in Deletion"
            errorMsg += ex.Message
            Throw New Exception(errorMsg)

        Finally
            SqlConn4.Close()
        End Try

    End Sub

Хотя это работает, на данный момент это только удаляет один флажок за раз, но делает большую часть того, что мне нужно было знать. Также спасибо Картеру за помощь в ответе на этот вопрос.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...