Need to delete rows from table if checkboxes are checked for row

Hello. I have a linkbutton that will delete individual rows from my gridview and update the database, however, I want to be able to make multiple selections via the checkboxes which appear on each row, and click just one button to delete all the checked rows. The following is from my aspx page:

  

<div style="float: right;">
                <asp:Button ID="btnLinkBack" runat="server" Text="Check Backlinks" />
                <asp:Button ID="btnApprove" runat="server" Text="Unhide" />
                <asp:Button ID="btnDisapprove" runat="server" Text="Hide" />
                 <asp:Button ID="btnDelete" runat="server" Text="Delete" />
            </div>
            <br /><br /><br />
            
            <asp:GridView ID="gvLink" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="false"
                DataKeyNames="AdvLinkID" DataSourceID="objDS" OnDataBinding="gv_DataBinding"
                OnPageIndexChanging="gv_PageIndexChanging" OnRowCommand="gv_RowCommand" OnRowDeleting="gv_RowDeleting"
                PagerSettings-Mode="NumericFirstLast" PagerSettings-PageButtonCount="10" PagerSettings-Position="TopAndBottom"
                PagerStyle-HorizontalAlign="right" Visible="false" Width="100%" PageSize="50">
                                
                <Columns>
                    <asp:TemplateField HeaderText="Select" ItemStyle-CssClass="GridHeader">
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" runat="server" />
                        </ItemTemplate>                    
                    </asp:TemplateField>
                    
                    <asp:TemplateField HeaderText="Link" SortExpression="SiteURL">
                        <ItemTemplate>
                            <a href='<%#Container.DataItem("SiteURL")%>' target="_blank">
                                <%#BusinessLogic.WebSite.TrimURL(Container.DataItem("SiteURL"), 40)%>
                            </a>
                            <br />
                            <span class="SiteTitle">
                                <%#Container.DataItem("SiteTitle")%>                            
                            </span>
                            <br />
                            <span class="SiteDescription">
                                <%#Container.DataItem("SiteDescription") %>
                            </span>
                            
                        </ItemTemplate>
                    </asp:TemplateField>
                    
                    <asp:TemplateField HeaderText="Reciprocal URL" SortExpression="ReciprocalURL" ItemStyle-Width="">
                        <ItemTemplate >
                            <a href="<%#Container.DataItem("ReciprocalURL")%>" target="_blank" title='<%#Container.DataItem("ReciprocalURL")%>'>
                                <%#BusinessLogic.WebSite.BreakReciprocalURL(Container.DataItem("AdvLinkID"), 40)%>                                
                            </a>
                        </ItemTemplate>
                    </asp:TemplateField>
                    
                    <asp:TemplateField HeaderText="Back Link" SortExpression="LinkBack" ItemStyle-HorizontalAlign="center">
                        <ItemTemplate>
                            <img src="../images/bullets/<%#CBool(Container.DataItem("LinkBack"))%>.gif" alt="link back status" style="text-align:center;"  id="linkback"/>
                        </ItemTemplate>
                    </asp:TemplateField>
                    
                    
                       <asp:TemplateField HeaderText="Last Checked" SortExpression="LastChecked">
                    <ItemTemplate>
          <asp:Label Text='<%# Eval("LastChecked", "{0:d}") %>' runat="server" ID="lblLastChecked" /><br />
          <asp:Button ID="btnEmail" OnClick="EmailWebmaster_Click" runat="server" Text="Email WebMaster" Visible="false" CommandArgument='<%#Container.DataItem("LinkID")%>' Font-Size="XX-Small" /><br />
          <asp:Label Text='Emailed on' runat="server" ID="Label1" Visible="false"/>
           <asp:Label Text='<%# Eval("LastEmailed", "{0:d}") %>' runat="server" ID="lblLastEmailed" Visible="false"/><br />
            <asp:Label Text='Check back in 5 days' runat="server" ID="Label2" Visible="false"/>
         <asp:Label Text='No email available. Contact webmaster through their website.' runat="server" ID="Label3" Visible="false"/>
           
                    </ItemTemplate>
                    </asp:TemplateField>

   
                    
                    <asp:TemplateField>
                        <ItemTemplate>
                            <div class="Highlight">
                                <asp:LinkButton ID="lnkHide" runat="server" CommandArgument='<%#Container.DataItem("AdvLinkID")%>'
                                    OnClick="HideUnHideLink" Text='<%#GetHideText(cbool(Container.DataItem("Approved")))%>'>
                                </asp:LinkButton>
                                <a href='adv_links_editbyuser.aspx?lid=<%#Container.DataItem("AdvLinkID")%>'>Edit</a>
                                <br />
                                <asp:LinkButton ID="lnkDelete" runat="server" CommandArgument='<%#Container.DataItem("AdvLinkID")%>'
                                    ForeColor="red" OnClick="DeleteLink" OnClientClick="return confirm('Are your sure to delete this link?')"
                                    Text="Delete">
                                </asp:LinkButton>
                            </div>
                        </ItemTemplate>
                    </asp:TemplateField>
                    
                   
                    
                </Columns>                                                            
            </asp:GridView>
            
            <br />
            <div style="float: left;">
                
            </div>
            <div style="float: right;">
                <asp:Button ID="btnLinkBack2" runat="server" Text="Check Backlinks" />
                <asp:Button ID="btnApprove2" runat="server" Text="Unhide" />
                <asp:Button ID="btnDisApprove2" runat="server" Text="Hide" />
                <asp:Button ID="btnDelete2" runat="server" Text="Delete" />
            </div>
            <br />
            <br />
        </td>
    </tr>
    
    </asp:Panel>
</table>
    <asp:ObjectDataSource ID="objDS" runat="server" DeleteMethod="Delete"
        SelectMethod="GetbyFieldValue" TypeName="BusinessLogic.AdvanceLink">
        <DeleteParameters>
            <asp:Parameter Name="AdvLinkID" Type="Int32" />
        </DeleteParameters>
        <SelectParameters>
            <asp:Parameter DefaultValue="WebSiteID" Name="field" Type="String" />
            <asp:ControlParameter Name="fieldValue" DefaultValue="0" ControlID="lstAdvanceSites" PropertyName="SelectedValue" Type="String" />
            <asp:Parameter DefaultValue="=" Name="criteria" Type="String" />
            <asp:Parameter DefaultValue="AdvanceCategoryID>0" Name="whereBy" Type="String" />
    
            <asp:Parameter DefaultValue="LastChecked" ConvertEmptyStringToNull="true" Name="sortBy" Type="String" />
            <asp:Parameter ConvertEmptyStringToNull="true" DefaultValue="" Name="tran" />
        </SelectParameters>
    </asp:ObjectDataSource>
  
1      Protected Sub gv_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
2            Dim grid As GridView = CType(sender, GridView)
3            grid.PageIndex = e.NewPageIndex
4            grid.DataBind()
5        End Sub
6    
7        Protected Sub gv_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs)
8    
9        End Sub
10       Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
11           Dim gvIDs As String = ""
12           Dim chkBox As Boolean = False
13           'Navigate through each row in the GridView for checkbox items
14           For Each gv As GridViewRow In gvLink.Rows
15               Dim deleteChkBxItem As CheckBox = CType(gv.FindControl("chkSelect"), CheckBox)
16               If deleteChkBxItem.Checked Then
17                   chkBox = True
18                   gvIDs += CType(gv.FindControl("AdvLinkID"), Label).Text.ToString + ","
19               End If
20           Next
21           Dim cn As New SqlConnection(DataFuncs.GetConnectionString)
22           If chkBox Then
23               Try
24                   Dim deleteSQL As String = _
25                  "DELETE from  WHERE employeeid IN (" + _
26                  gvIDs.Substring(0, gvIDs.LastIndexOf(",")) + ")"
27                   Dim cmd As SqlCommand = New SqlCommand(deleteSQL, cn)
28                   cn.Open()
29                   cmd.ExecuteNonQuery()
30                   gvLink.DataBind()
31               Catch Err As SqlException
32                   Response.Write(Err.Message.ToString)
33               Finally
34                   cn.Close()
35               End Try
36           End If
37       End Sub
38   

 I had added the above for btnDelete click from some code I found online.  Can someone help me complete this? The main id is AdvlinkID which identifies the row in the table.

Many thanks. 


Scot King
SEO Software Tool | Search Engine Optimization

"Get your page rank high"
0
sking
1/22/2009 7:49:55 AM
asp.net.presentation-controls 72751 articles. 1 followers. Follow

2 Replies
283 Views

Similar Articles

[PageSpeed] 14

 Your on the right track for sure. I modified your code slightly to fire a method every time the check box is true, i think i have read your code correctly
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim gvIDs As String = ""
        Dim chkBox As Boolean = False
        'Navigate through each row in the GridView for checkbox items
        For Each gv As GridViewRow In gvLink.Rows
            If CType(gv.FindControl("chkSelect"), CheckBox).Checked Then
                'Modified to create a method to run on each Checked=true checkbox
                DeleteItem(CType(gv.FindControl("AdvLinkID"), Label).Text.ToString)
            End If
        Next
    End Sub
    'Runs the sql command to delte the employee on each true checkbox, returns a Boolean wether or not complete. 
    'You could change this to a string to send back an error message if you would prefer.
    Private Function DeleteItem(ByVal employee As String) As Boolean
        If String.IsNullOrEmpty(employee) Then
            Return False
        End If
        Dim completed As Boolean = False
        Dim cn As New SqlConnection(DataFuncs.GetConnectionString)
        Dim cmd As SqlCommand = New SqlCommand()
        cmd.Connection = cn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "DELETE from  WHERE employeeid =@employeeID"
        cmd.Parameters.AddWithValue("@employeeID", employee)
        Try
            cn.Open()
            cmd.ExecuteNonQuery()
            completed = True
        Catch Err As Exception
            completed = False
        Finally
            cn.Close()
        End Try
        Return completed
    End Function

 

 


Please mark post as answer
Obilit.com - Progressive Web Methodologies

My Blog
0
nvanhaaster
1/22/2009 10:51:36 AM

The keyval seems to get the integer I need to pass to the delete routine.  It deletes the links from 3 databases. 

 

Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click, btnDelete2.Click

        Deletelinks()

    End Sub
    Private Sub Deletelinks()

        Dim grid As GridView = Me.gvLink

        Dim keyVal As String

        For Each itm As GridViewRow In grid.Rows
            keyVal = grid.DataKeys(itm.RowIndex).Value
            If CType(itm.FindControl("chkSelect"), CheckBox).Checked Then

                AdvanceLink.Delete(keyVal, True)

            End If
        Next

        grid.DataBind()
        Me.lblMsg.Text = "All selected links deleted"

    End Sub


Scot King
SEO Software Tool | Search Engine Optimization

"Get your page rank high"
0
sking
1/24/2009 9:11:50 PM
Reply:

Similar Artilces:

adding / deleting table rows, and accessing controls within added rows
Hi everyone,I would like to know what is a good and simple way to achieve this using asp.net.  Basically i would like the ability to add and delete rows, preferably table rows.  Against each row is its delete button, hitting it will delete the corresponding row.  There is only 1 Add button to add a new row.  In each row, there are say 2 textboxes.  When i hit, say a calculate button, i wish to be able to access all the available textboxes in all the available rows in the event handler, and say just output a sum.If GridView is suggested, could you please explain why i...

javascript: check all check box in a perticular row , when i check a checkbox i that perticuler row
Hi Friends,I have a gridview. and I am having checkboxes in all the columns and all the rows. Like it is about selecting subjects.My Problem is when I select a Checkbox in First column of any row, all the checkboxes in that particular row should also be selected.How can I do this... . I have done all checkboxes checked for column, but no idea about row.Please guide.Thanks. Hi, this can be done with the help of jQuery, a great & free javascript library. Take a look at this article: Check All Checkboxes in GridView using JQuery. Grz, Kris.Read my blog. Handy Firefox plugins for web dev...

DataGrid with checkbox next to every row, update checked rows in Database table
I have a datagrid with checkbox column which is bit datatype 0 or 1 which show up on ASP page as checked by default as 1 , I want users to  uncheck certain rows and hit a refresh button right next to datagrid , refresh will do a update in the table and change the bit column value to 0 in table for uncheck rows. any suggestions, I found  something below but this update button next to every row in a column, I want a universal button outside data gird whihc can update all rows in the orignal table.   Private Sub DataGrid1_ItemCommand(ByVal sour...

Deleting rows from one table based upon rows in another table
I need to delete rows from table1 based on rows in table2. table1 has 1.5 million rows from which I need to delete 20,000 existing in table2. The table structures are the same and I must exactly match 10 (of the 15) columns in the tables. I also need to limit the number of rows being worked on, in a single transaction, to 500 or so. Hi Mike, try the following: set rowcount 500 DELETE table1 from table1 t1,table2 t2 where t1.col1=t2.col1 and t1.col2=t2.col2 and t1.col3=t2.col3 and ........ t1.col10=t2.col10 HTH. Regards P:S You must re-execute the DML statement above 40 time...

Is having a trigger that inserts a row in Table 'A', when a row in same table is inserted by ADo.Net code?
I want to insert a row for a Global user  in Table 'A' whenever ADO.Net code inserts a Local user row into same table. I recommended using a trigger to implement this functionality, but the DBA was against it, saying that stored proecedures should be used, since triggers are unreliable and slow down the system by placing unecessary locks on the table. Is this true OR the DBA is saying something wrong? My thinking is that Microsoft will never include triggers if they are unreliable and the DBA is just wanting to offload the extra DBA task of triggers to the programmer so that a s...

How to add a footer row to a table after deleting all footer rows
I'm sure this is a very easy thing to do, but I can't figure out how to do it. I have a table, and I deleted all the footer rows.  Now I would like to add one footer row.  How do I do that? If I right-click on the detail row and select Insert Row Below, it is, of course, another detail row. I'm stumped -- thanks for any help you can give!Cynthia Do you have groups in your table?  You should be able to right click on any table row and toggle the corresponding menu item to show the table header, details or footer.  It is in the right click menu includ...

ADO.net problem: i can not view image data for the rest of my table rows except the image for the first row but i can read all the other non image fields for all rows.
Hi i have a table with the following fields imgid............int imgdata........image imgtitle.........varchar(max) imgType........varchar(max) imgLength.....bigint incident_id.....int i have no problem with uploading the image but viewing the uploaded image(s) in a gridview has caused me great pain. The probelm is i have two pages. page1 grabs the image to display and page2 has a gridview that displays the grabed image. I wanted to have an sql statement like SELECT * FROM mytable WHERE incident_id=someValue. IF i have 5 records in this table and i view page2 ...

Add new controls to a gridview row; when editing that row using the edit row feature in the gridview control.
Hi all  I have a questions that looks hard / complex to me, and i know you can help me in this. Q {  I have row in a Gridview and i have an edit option to it. I press the edit button, to edit the values in that row and update data all the way back to the database. Now when i press the edit button, i want a drop down list to be displayed that contain values for a particular field in my grid view. (for now only plain text boxes appear.) } I hope you understand my question, all i need to do is replace the text box controls with a dropdown list when i am editing a row in ...

I want to select top 3 rows except the first from 4 rows of a Table. It should select from top 2 row,top3 row and top4 row.
 Hi, Let say I've 4 rows in a table. I want to select top 3 rows except the first from 4 rows of a Table. It should select from top 2 row,top3 row and top4 row. Thanks in advance Asghar Ali Mohammed http://www.aliwebdev.com(Web Designer and Developer)Do not forget to "MARK AS ANSWER" on the post that helped you. If you can use Linq, you can use Skip. http://msdn.microsoft.com/en-us/vcsharp/aa336757.aspxThanks, EdMicrosoft MVP - ASP/ASP.NET Hii dear..U can fire the Query select Top(3) from Table1 order by id desc.. "A conclusion is whe...

Delete row and delete from table
Hi I need, after delete a grid row, execute a delete statmentProtected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand Dim advogado As StringIf (e.CommandName = "Apagar") Thenadvogado = RTrim(e.CommandArgument.ToString)Apaga_Processos(advogado)End Ifend subPrivate Sub Apaga_Processos(ByVal advogado As String)Dim conn As SqlConnectionDim comm As SqlCommandDim connectionString As String = ConfigurationManager.ConnectionStrings("mssql2.tuganet.com").ConnectionStringconn = New Sql...

Need help adding dynamic check boxes to rows returned to a datagrid/datarepeater/etc and checking for values in the checkbox
Here is my scenario,I have Users that have Friends.  They can add friends, and remove friends.I want to populate an ASP.Net control (data grid, repeater, whatever is best) with the friend's name and then provide a column with checkboxes.  The submit button will perform the Remove.When I Remove, I want to iterate through each row and if the row has a checked checkbox, grab the friend's ID from that line and stuff it into a string for later use (delete query).Can anyone make suggestions on how to code this, point me to some articles, or offer any other suggestions?Thanks for the help...

How to delete Checked CheckBox Rows in DataGridView
 Hello  I have a gridview with 4 columns.1st columns is the checkboxes,which I can either select all or select any perticular row.2nd is title,3rd it comment text and 4rth is Permission.I am being able to select/unselect all checkboxes by writing a java scripts.Now after the gridview I have 3 buttons.1-Delete,2-Deny,3-Approved.And I also have 3 stored procedure for each of them.My problem is after selecting checkbox  nothing is being deleted.I debug the code and every time if (cb.Checked) is unchecked.also its not traversing the loop,and after if checking it comes out of the...

Update row in Table A from row in Table B
Hello, I have 2 tables.... table A and table B. Ok, In a stored procedure, I pass in an int value @ID I want to get the row from Table B WHERE ID =@ID....and then UPDATE the Row in Table A that has the same ID...with the values from table B. Table A ID | Col1 | Col2 ----------------------- 2 a a Table B ID | Col1 | Col2 ----------------------- 2 b b I would like to update A.Col1 with B.Col1 and A.Col2 with B.Col2 Can someone help me out with this syntax? Thanks a lot. update tableA ...

how to check all the row level checkbox when header level checkbox is checked
hello i m working on one site which requires the functionality like yahoo, that is when we check header level check box then all row level checkbox is checked.i m sending my code here....<script language="javascript" type="text/javascript">        function Check(chk)        {          alert("abc");            if(document.form1.HeaderLevelCheckBox.checked==true)    ...

Web resources about - Need to delete rows from table if checkboxes are checked for row - asp.net.presentation-controls

Quick Tip Friday: Create Checklists Faster with Auto-Checkboxes
/ We know a lot of Evernote users love checkboxes for to-dos, grocery lists, and more. Creating checkboxes in Evernote is easy: you can add them ...

Group sues Michigan secretary of state over citizenship checkboxes for voters
... rights coalition filed a federal lawsuit today in Detroit challenging Secretary of State Ruth Johnson’s decision to have U.S. citizenship checkboxes ...

Evernote for BlackBerry 10 updated with checkboxes, image and audio attachments
Evernote has updated its recently launched app for the BlackBerry 10 platform with new features, alongside speed improvements and two-step verification. ...

Add checkboxes to an Excel spreadsheet
Tgood37 asked the Answer Line forum how to add checkboxes to Excel spreadsheets, and how to make sure that checking a box will have an effect. ...

Solving Twitter and LinkedIn’s Ad Problem: It’s Time to Ditch the Checkboxes
Last week was a big one for social media giants Twitter and LinkedIn. They admitted to their investors and to the world that their display advertising ...

Simple trick for testing forms full of checkboxes with django
... testing style. What matters is that you have tests. Image via Wikipedia But what do you do when you want to test a form with a bunch of checkboxes? ...

Checkboxes that kill your product
Alexander Limi / Alex Limi : Checkboxes that kill your product — (To read this article with its formatting and typography intact, click here) ...

Evernote for BlackBerry 10 updated with checkboxes, image and audio attachments
... 10 platform with new features, alongside speed improvements and two-step verification. Among the new features is the ability to insert checkboxes ...

Bento for iPad for iPad on the iTunes App Store
Read reviews, get customer ratings, see screenshots, and learn more about Bento for iPad on the App Store. Download Bento for iPad and enjoy ...

Facebook Users in Brazil and India Can Syndicate Their Profiles to Orkut
Facebook users in Brazil and India can now connect their profiles with their account on Orkut , Google’s existing social network. Those who link ...

Resources last updated: 11/24/2015 10:37:02 PM