Using HoverMenuExtender with ASP.NET ListView to Update, Delete and Insert Records

Posted by: Suprotim Agarwal , on 8/22/2008, in Category ASP.NET
Views: 70791
Abstract: In this article, we will explore how to associate a HoverMenuExtender with a ListView control to update and delete records. The Listview control in this sample will also contain the functionality to add new records.
Using HoverMenuExtender with ASP.NET ListView to Update, Delete and Insert Records
 
The ListView control is a new data control available in ASP.NET 3.5 and is quiet similar to the GridView and Repeater control. The GridView uses row fields to display data, whereas the ListView control displays data using user-defined templates. Moreover ListView can edit and select data whereas Repeater cannot. ListView provides more flexibility in displaying data, in comparison to what the GridView and Repeater give.
The ASP.NET AJAX HoverMenuExtender can be attached to any ASP.NET WebControl. The extender associates the ASP.NET control with a panel that is popped up to display additional content, whenever the user moves the mouse cursor over the ASP.NET control.
In this article, we will explore how to associate a HoverMenuExtender with a ListView control to update and delete records. The Listview control in this sample will also contain the functionality to add new records.
Step 1: Open VS 2008. Click File > New > Website. Choose ASP.NET Website from the list of installed template, choose target platform as .NET Framework 3.5, choose the desired language and enter the location where you would like to store the website on your FileSystem. I have created a folder called VS2008 Projects, so the location over here is C:\VS2008 Projects\ ListViewDemoHoverExtender. After typing the location, click OK.
Step 2: Open Default.aspx. Switch to the Design mode of Default.aspx. Open the toolbox (Ctrl+Alt+X) > Data Tab > Drag and drop a ListView control to the form. If you look at the ‘Source’ view, the ListView tag looks as shown below:
        <asp:ListView ID="ListView1" runat="server">
        </asp:ListView>
We will now display data in the ListView by binding it to the datasource.
Step 3: Click on the smart tag or right click ListView > Show Smart Tag > Choose a DataSource > New Data Source… > Select Database. We will keep the default ID for SqlDataSource, SqlDataSource1 and click OK.
Step 4: On clicking Ok, you will be presented with a ‘Configure Data Source’ wizard. Click on ‘New Connection’ to open the ‘Add Connection’. Type your ‘Server Name’ and ‘Select a database Name’ to connect to. Over here, I have typed (local) as the ServerName and the database I am connecting to is Northwind. Click on ‘Test Connection’ to make sure that there are no errors connecting to the server. Click Ok.
Step 5: In your ‘Configure Data Source’, click Next. You will be displayed an option of saving the connection string to the configuration file. Select the checkbox ‘Yes, save this connection as:’ , type a name for the connectionstring ‘NorthwindConnectionString’ and click Next.
Step 6:  In the ‘Configure Select Statement’ > Select ‘Specify Columns from Tables or Views’ radiobutton. Select ‘Products’ table in the Name and choose ProductID, ProductName and Discontinued as column names as shown below:
List View Data Source
Click Next > ‘Test Query’ to preview data > click Finish. The wizard adds a SqlDataSource control to the page and the ListView is binded to this data source.
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1">
 
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
    SelectCommand="SELECT [ProductID], [ProductName], [Discontinued] FROM [Alphabetical list of products]">
</asp:SqlDataSource>
If you check your web.config, the connection string is added as shown below:
<connectionStrings>
      <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
After setting up the SQLDataSource, in the next step, we will now display the data in the ListView
Step 7: Add a LayoutTemplate to the ListView as shown below. The Layout template defines the root container for the output generated and contains other Item template, Group template or DataPager object. The Item Template defines the mark up needed to generate each item for each record.
<LayoutTemplate>
    <table>
        <tr>
            <td>
                <table border="1" style="border-width:1; border-color:Black">
                    <tr>
                        <th></th>
                        <!-- Width 100 px to accomodate the HoverMenu Popup -->
                        <th style="width:100px">ProductID</th>
                        <th>ProductName</th>
                        <th>Discontinued</th>
                    </tr>
                        <tr runat="server" ID="itemPlaceholder">
                    </tr>
                </table>
            </td>
        </tr>
            <!--Data Pager -->
        <tr>
            <td>
                <asp:DataPager runat="server" ID="listViewPager" PageSize="5">
                 <Fields>
                      <asp:NumericPagerField ButtonCount="10"
                       PreviousPageText="<--" NextPageText="-->" />
                 </Fields>
                </asp:DataPager>
            </td>
        </tr>
    </table>
</LayoutTemplate>
The ListView control does not have paging capabilities. It is the DataPager control that provides it with Paging capabilities. The advantage of having a separate control for paging is that you can decide the look and feel of the pager and also position it anywhere on the page, separate from the ListView control.
Step 8: To display data, we will declare the <ItemTemplate>. We will also create the HoverMenuExtender in the <ItemTemplate> to associate each row of the ListView with a popup, to display links for Editing and Deleting data.
Just before performing this step, add a <ScriptManager> tag before the ListView.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1">
...
</asp:ListView>
Drag the HoverMenuExtender from the AjaxControlToolkit to the form. After setting the properties of the HoverMenuExtender, the mark up needed to generate each item for each record is shown below:
<ItemTemplate>
    <tr>
        <td>    
            <cc1:HoverMenuExtender ID="HoverMenuExtender1" runat="server"
                TargetControlID="lblProdName" PopupControlID="panelPopUp"
                PopDelay="20" OffsetX="-100" OffsetY="-5">
            </cc1:HoverMenuExtender>
            <asp:Panel ID="panelPopUp" runat="server">
                <table>
                    <tr>
                        <td>
                            <asp:Button ID="btnEdit" runat="server"
                            CommandName="Edit" Text="Edit" />
                        </td>
                        <td>
                             <asp:Button ID="btnDelete" runat="server"
                             CommandName="Delete" Text="Delete" />
                        </td>
                    </tr>
                </table>
            </asp:Panel>
         </td>
         <td>
             <asp:Label ID="lblProdID" runat="server"
              Text='<%# Eval("ProductID") %>' />
          </td>
          <td>
             <asp:Label ID="lblProdName" runat="server"
              Text='<%# Eval("ProductName") %>' />
          </td>
          <td>
             <asp:Label ID="cbDiscontinued" runat="server"
              Text='<%# Eval("Discontinued") %>' />
          </td>
    </tr>
</ItemTemplate>
Note: When we dropped the HoverMenuExtender, the AjaxControlToolkit assembly was registered using the following mark up:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
 
Step 9: Up till here, we have created functionality to display data in the ListView as well as pop-up the panel when the user hovers over ‘ProductName’ column using the HoverMenuExtender. We will now move ahead and generate the markup for Inserting, Updating and Deleting the records in the ListView.
Follow these sub-steps. Set the InsertCommand and UpdateCommand property of the SqlDataSource control to the SQL statements shown below, to enable updating and inserting records in the ListView. The mark up for the SqlDataSource will look similar to the following:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
    SelectCommand="SELECT [ProductID], [ProductName], [Discontinued] FROM [Alphabetical list of products]"
    InsertCommand = "INSERT INTO [Products] (ProductName, Discontinued)VALUES(@ProductName,@Discontinued)"
    UpdateCommand = "UPDATE [Products] SET [ProductName] = @ProductName WHERE [ProductID] = @ProductID"
    DeleteCommand = "DELETE FROM [Products] WHERE [ProductID]=@ProductID">
     <InsertParameters>
        <asp:Parameter Name="ProductName" Type="String" />
        <asp:Parameter Name="Discontinued" Type="Byte" />
     </InsertParameters>           
    <UpdateParameters>
        <asp:Parameter Name="ProductName" Type="String" />             
        <asp:Parameter Name="ProductID" Type="Int32" />
    </UpdateParameters>
    <DeleteParameters>
        <asp:Parameter Name="ProductID" Type="Int32" />
    </DeleteParameters>
</asp:SqlDataSource>
Next, create the markup for the EditTemplate and InsertTemplate as shown below:
<EditItemTemplate>
   <tr>
      <td>
         <asp:Button ID="btnUpdate" runat="server"
          CommandName="Update" Text="Update" />
         <asp:Button ID="btnCancel" runat="server"
          CommandName="Cancel" Text="Cancel" />
      </td>
      <td>
         <asp:Label ID="lblProdIDReadOnly" runat="server"
          Text='<%# Bind("ProductID") %>' /></td>
       <td>
         <asp:TextBox ID="txtEditProdName" runat="server"
          Text='<%# Bind("ProductName") %>' />
      </td>
   </tr>
</EditItemTemplate>
 
<InsertItemTemplate>
   <tr>
      <td>
      </td>
      <td>
         <asp:Button ID="btnInsert" runat="server" CommandName="Insert"
          Text="Insert" />
         <asp:Button ID="btnInsertCancel" runat="server" CommandName="Cancel"
          Text="Cancel" />
      </td>
      <td>
         <asp:TextBox ID="txtInsertProdName" runat="server"
          Text='<%# Bind("ProductName") %>' />
      </td>
      <td>
         <asp:CheckBox ID="cbInsertDiscontinued" runat="server"
          Checked='<%# Bind("Discontinued") %>' />
      </td>
   </tr>
</InsertItemTemplate>
The last and most important step is to mention the ‘DataKeyNames’ and the ‘InsertItemPosition’ in the ListView as shown below:
<asp:ListView ID="ListView1" runat="server"
DataSourceID="SqlDataSource1" DataKeyNames="ProductID" InsertItemPosition="LastItem">
 
You are now ready to run the application and test the functionality. Run the application by pressing F5 and hover your mouse over the ProductName to display the HoverMenu as shown below:
Hover Menu
When you hit Edit, the row displays the Update and Cancel links in the right column in Edit mode.
UpdateCancelHover
You can also delete rows, but if you try deleting an existing row in this example, you will get a Reference Constraint violation error as follows:
The DELETE statement conflicted with the REFERENCE constraint "FK_Order_Details_Products". The conflict occurred in database "Northwind", table "dbo.Order Details", column 'ProductID'. The statement has been terminated.
So to test ‘Deletion’, add a new record using the Insert Row displayed in the last row (placed here as a result of the InsertItemPosition in ListView), and then delete that newly added product record.
Well that is pretty much it. We saw how to associate the HoverMenuExtender with the ListView control to update and delete records. We also saw how to insert new rows using the ListView control. And if you observed, we did all these operations using just templates, without writing a single line of code. You can play around with this sample to customize it to your requirement. The source code of the article can be downloaded from here. I hope this article was useful and I thank you for viewing it. 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Ralph on Saturday, October 11, 2008 6:49 AM
Fantastic implementation. The connection string though looks tied up in the example (there is no space between "add name" )

<addname="NorthwindConnectionString"connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated
Comment posted by Suprotim Agarwal on Monday, October 13, 2008 8:01 AM
Thanks. The spaces have been added.
Comment posted by Srujan on Saturday, November 22, 2008 5:26 AM
It's so nice,very helpful.
How can i download the source code for this article?
Comment posted by Suprotim Agarwal on Sunday, November 23, 2008 10:22 PM
Srujan: The download link has been fixed. Thanks.
Comment posted by ajay on Monday, November 24, 2008 7:47 AM
Better to use Business Logic(C#) to performs all operation in List View
Comment posted by abeer hashmi on Tuesday, March 3, 2009 12:50 AM
superb code but I dinn understn
Comment posted by AlwaysVisibleControl Demonstration AJAX control in asp.net 2008 on Tuesday, March 31, 2009 12:55 AM
AlwaysVisibleControl Demonstration AJAX control in asp.net 2008
Comment posted by harsh on Monday, May 11, 2009 10:33 AM
send me inserting an item in list view control
Comment posted by AhernCK on Sunday, November 1, 2009 9:44 PM
This is just I was looking for, thank you very much
Comment posted by brite on Thursday, December 30, 2010 4:11 AM
Hi,
    I tried your code, when i clicked the Edit  not working,  'WebForm_PostBackOption is undefinded message is shown how should i overcome this error
Comment posted by Jeet Verma on Saturday, December 31, 2011 3:34 AM
Very informative post. Its really helpful for me and beginner too. Check out this link too its also having a nice post with wonderful explanation on Ajax Toolkit HoverMenuExtender Control in ASP.Net...

http://mindstick.com/Articles/037b835c-a670-4200-8096-77771cf006e1/?Ajax%20Toolkit%20HoverMenuExtender%20Control%20in%20ASP.Net

Thanks
Comment posted by krishnaveni on Friday, December 28, 2012 12:29 AM
hai

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel