0

Using confirmation before delete from ListView using C#. I have a ListView with CheckBox in it and I want to Delete the Items/Records from ListView which are selected with CheckBox in to it.

i.e Multiple select items and then Delete these Multiple Records from ListView I use SqlDataSource to bind data :) Any Idea?

<asp:ListView runat="server" ID="listBaiBao" OnSorting="listBaiBao_Sorting">
        <LayoutTemplate>
            <table id="tblBaiBao" class="table table-bordered table-hover tablesorter">
                <tr runat="server">
                    <th runat="server"><asp:CheckBox OnCheckedChanged="chkAll_CheckChanged" runat="server" ID="chkAll"/></th>
                    <th runat="server"><asp:LinkButton CommandName="Sort" CommandArgument="TenBaiBao" ID="lnkTen" runat="server">Tên bài báo <i class="fa fa-sort"></i></asp:LinkButton></th>
                    <th runat="server"><asp:LinkButton runat="server" CommandName="Sort" CommandArgument="SoBao" ID="lnkSoBao">Số báo <i class="fa fa-sort"></i></asp:LinkButton></th>
                    <th runat="server"><asp:LinkButton runat="server" CommandName="Sort" CommandArgument="NamPhatHanh" ID="lnkNamPH">Năm phát hành <i class="fa fa-sort"></asp:LinkButton></i></th>
                    <th runat="server"><asp:LinkButton runat="server" CommandName="Sort" CommandArgument="TacGia" ID="lnkTacGia">Tác giả <i class="fa fa-sort"></i></asp:LinkButton></th>
                    <th runat="server"><asp:LinkButton runat="server" CommandName="Sort" CommandArgument="DuongDanFile" ID="lnkDuongDan">Đính kèm <i class="fa fa-sort"></i></asp:LinkButton></th>
                    <th runat="server">Edit</th>
                </tr>
                <tr id="ItemPlaceholder" runat="server">
                </tr>
            </table>
            <asp:DataPager ID="ItemDataPager" runat="server" PageSize="10">
                <Fields>
                    <asp:NumericPagerField CurrentPageLabelCssClass="pagenum-active" NumericButtonCssClass="pagenum" NextPreviousButtonCssClass="pagenum" ButtonCount="2" />
                </Fields>
            </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <asp:CheckBox runat="server" ID="chk"/>
                </td>
                <td>
                    <asp:Label runat="server" Text='<%# Eval("TenBaiBao") %>'></asp:Label></td>
                <td>
                    <asp:Label runat="server" Text='<%# Eval("SoBao") %>'></asp:Label></td>
                <td>
                    <asp:Label runat="server" Text='<%# Eval("NamPhatHanh") %>'></asp:Label></td>
                <td>
                    <asp:Label runat="server" Text='<%# Eval("TacGia") %>'></asp:Label></td>
                <td>
                    <asp:Label runat="server" Text='<%# Eval("DuongDanFile") %>'></asp:Label></td>
                <td>
                    <a class="btn btn-info" href='index.aspx?page=suabaibao&id=<%# Eval("MaBaiBao") %>'><i class="fa fa-edit"></i></a>

                </td>
            </tr>
        </ItemTemplate>

    </asp:ListView>
3
  • I'm not sure to understand your question.Is List bounded to a datasource??What is your goal hide some fields or delete from datasource(SQL,MYSQL or XML...) your data and then rebind your list??please give us more info please Commented Apr 26, 2014 at 18:12
  • @makemoney2010 i use SqlDataSource to bind. Yes i want to delete from datasource then rebind my list. Commented Apr 27, 2014 at 5:05
  • check update in my previous response Commented Apr 29, 2014 at 19:24

2 Answers 2

1

using property name of each checkbox to setup the id of your record. When youchose multiple check box and click on delete filter all checbox checked and read from property name each id the pass those id to you query to delete recordo.

then re-populate your list and rebind to ListItem :)

Take care that i have no idea how is your database i suppose that you have an id as primary key :)

UPDATE SOLUTION TWO STEP TO ACHIEVE YOUR GOAL:

STEP ONE:

Within item tempalte add tooltip and bind it to ID of items of the record:

<asp:checkbox runat="server" id="yourID" ToolTip="<%Eval("ITEMID")%>/>

You will use this data to store the primary key of your record in order to get it in step 2 I assume that you have a button to delete all selected record so in its event on click you may use this code to get all the ids of all checked checkbox

  Protected Sub btnDeleteAllChecked_Click(sender As Object, e As EventArgs)

    Dim ListItems As New List(Of Integer)
    For Each el In listBaiBao.Items
        For Each item In el.Controls
            If TypeOf item Is CheckBox Then
                If DirectCast(item, CheckBox).Checked = True Then
                    ListItems.Add(DirectCast(item, CheckBox).ToolTip)
                End If
            End If
        Next
    Next
    'Delete record from your database 
    Using cnn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("YOURCONNECTIONSTRING").ToString)
        'open the connection
        If cnn.State = ConnectionState.Closed Then cnn.Open()
        'formatting your query string 
        Dim Query As String = String.Format("DELETE FROM YOURTABLENAME WHERE ID IN({0})", String.Join(",", ListItems.ToArray()))

        Using cmd As New System.Data.SqlClient.SqlCommand(Query, cnn)
            'execute delete action, update your select and rebind your list view
            Try
                With cmd
                    .CommandType = CommandType.Text
                    'delete action
                    .ExecuteNonQuery()
                End With
                'ONCE DELETE HAS BEEN PERFORMED CHANGE CMD SELECT STATEMENT AD USE THE SAME COMMAND 
                'TO REBIND A DATABASE OR A DATABLE AS YOU PREFERE LIKE HERE
                Dim Da As New System.Data.SqlClient.SqlDataAdapter(cmd)
                Dim Ds As New System.Data.DataSet
                Da.Fill(Ds)
                'REBIND CONTROL
                listBaiBao.DataSource = Ds.Tables(0)
                listBaiBao.DataBind()
            Catch ex As Exception
                Response.Write(ex.Message)
            End Try
        End Using
    End Using

End Sub

This is based on what i know. I hope it help you. If it solve your issue mark it as answers.If you use Entity framework or any other way to bind your control i need to know in order to help you

Sign up to request clarification or add additional context in comments.

3 Comments

I don't know VB. So i'm trying to understand your code :)
using this link to convert from vbg to c# it work very fine : developerfusion.com/tools/convert/vb-to-csharp and if it work for you mark it as answer
One more question, I have a checkbox ID = "chkAll" inside LayoutTemplate of ListView. Why can't i see it in code behind?
0

Written from mind not checked from codes.. If i don't remember wrong ListView has RemoveAt() method which remove item at given index..

with this :

foreach ( ListViewItem item in yourListView.CheckedItems)
{
  yourListView.RemoveAt(yourListView.Items.IndexOf(item));

  //or with another option : 

  yourListView.Remove(item);
}

EDIT : After seen @makemoney2010 's comment..

What kind of Data collection you bind to your ListView? An IList, A DataTable / DataSet, an IDictionary, A DataView? or Something else that you can use in Asp.Net?

Any of i told has Index Implementation on it.. You can use these index implementations..

And as a best practise (to avoid unwanted results) If you bind your data from an Sql based datasource you should implement a primary key..Then everything will be better

10 Comments

i can't find property CheckedItems @@
if you can't find then it means you don't have a listview with checkbox (at least it doesn't have any column with checkboxes).. So, first correct your question..second, if you dont have checkbox column inside listview, then simply create a boolean collection and manage with your "oncheckedchanged" event which you implement with your checkboxes
third - as the needs of your project implementation doesn't so clear - there are many many ways to do something with codes..as an example if you want to remove the row/item from your listview when checkbox checked or unchecked then you can investigate the checkbox's index no/row no or parent container and then find the related listviewitem and remove it..as you see first you need to clear your needs and go on that way..then it can be simplifier and everyoner can help you in a better way..
@sihirbazzz we're talking about listview aspnet not listview form control.Are little bit different.He use a custom template so he cannot do it.He need to intercept some value from control and then do the query to delete with those parameters nothing else then rebind the control too
@makemoney2010 yeah i try to tell a way to do your way..If AspNet builds on framework then it means he can put a global (on .cs page) boolean array variable as the same count of checkboxes and listview items..When someone change checkbox's state then state pops the array and ArrayIndex can pass to ListView.Delete/ listview.remove() function..Am i right? (of course this is the long way)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.