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:
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:
When you hit Edit, the row displays the Update and Cancel links in the right column in Edit mode.
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.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn