Category: Asp.NET

ListView Control in ASP.NET 3.5

The ListView is an extremely flexible data-bound control that renders its content based on the templates you define. Unlike the Repeater, the ListView adds higher level features such as selection and editing, which work in the same way as those in the GridView. But unlike the GridView, the ListView does’t support a field based model for creating quick and easy grids with a minimum of markup.

ListView is a new addition in ASP.NET 3.5. ListView can literally replace all other data binding controls in ASP.NET. ListView control makes data binding easier than previous controls. It has included styling with CSS, flexible pagination, and sorting, inserting, deleting, and updating features.

The most common reason for using the ListView is to create an unusual layout. For Example , to create a table that places more than one item in the same row, or to break free from table based rendering altogether. When building a page to display large amounts of data, ASP.NET developers usually turn to the GridView first and use the ListView in most specialized scenarios.

ListView Templates:

Templates control certain aspects of the ListView control’s generated HTML. Templates are required with ListView; they are optional with other data controls. These templates provide complete control over the output; that is, all aspects of the ListView’s generated markup are controlled via templates.

The following list offers details about the numerous templates available with ListView.

  1. AlternatingItemTemplate: Defines how alternating items are displayed.
  2. EditItemTemplate: Defines the presentation for an item when it is edited.
  3. EmptyDataTemplate: Specifies the content to display for empty individual items.
  4. EmptyItemTemplate: Specifies the content to display for empty group items.
  5. GroupSeparatorTemplate: Specifies the content to display between groups.
  6. GroupTemplate: Defines the content for groups. This template is a placeholder for the data displayed for individual group items (when data is grouped).
  7. InsertItemTemplate: Defines the presentation for a new item being inserted into the data set.
  8. ItemSeparatorTemplate: Defines the content to display between individual data items.
  9. ItemTemplate: Defines the data to display for single items.
  10. LayoutTemplate: Defines the main presentation features for the control. This root template contains placeholders that are replaced by what is defined by ItemTemplate and GroupTemplate.
  11. SelectedItemTemplate: Specifies the content to display when users select items.

In this article we will discuss features in ListView step by step.

  1. Data Binding
  2. Data Pager
  3. Add, Edit and Delete

In Data Binding we will bind ListView from database. To show data use ItemTemplate and AlternateItemTemplate show alternative row with different styles.

Data Binding –

AlternateItemTemplate & ItemTemplate :

<asp:ListView ID=”VendorListView” runat=”server” DataKeyNames=”VendorId”

DataSourceID=”SqlDataSource1″ onitemcommand=”VendorListView_ItemCommand”

onsorting=”VendorListView_Sorting” InsertItemPosition=”LastItem”>

<AlternatingItemTemplate>

<tr style=”background-color: #FFFFFF; color: #284775;”>

<td><asp:Label ID=”VendorIdLabel” runat=”server” Text='<%# Eval(“VendorId”)%>’ /></td>

<td><asp:Label ID=”VendorFNameLabel” runat=”server” Text='<%# Eval(“VendorFName”) %>’ /></td>

<td><asp:Label ID=”VendorLNameLabel” runat=”server” Text='<%# Eval(“VendorLName”) %>’ /></td>

<td><asp:Label ID=”VendorCityLabel” runat=”server” Text='<%# Eval(“VendorCity”) %>’ /></td>

<td><asp:Label ID=”VendorStateLabel” runat=”server” Text='<%# Eval(“VendorState”) %>’ /></td>

<td><asp:Label ID=”VendorCountryLabel” runat=”server” Text='<%# Eval(“VendorCountry”) %>’ /></td>

<td><asp:Label ID=”PostedDateLabel” runat=”server” Text='<%# Eval(“PostedDate”) %>’ /></td>

<td><asp:Label ID=”VendorDescriptionLabel” runat=”server” Text='<%# Eval(“VendorDescription”) %>’ /></td>

<td><asp:LinkButton ID=”LinkButtonEdit” runat=”server”CommandName=”Edit”>Edit</asp:LinkButton></td>

</tr>

</AlternatingItemTemplate>

<ItemTemplate>

<tr style=”background-color: #E0FFFF; color: #333333;”>

<td><asp:Label ID=”VendorIdLabel” runat=”server” Text='<%# Eval(“VendorId”)%>’ /></td>

<td><asp:Label ID=”VendorFNameLabel” runat=”server” Text='<%# Eval(“VendorFName”) %>’ /></td>

<td><asp:Label ID=”VendorLNameLabel” runat=”server” Text='<%# Eval(“VendorLName”) %>’ /></td>

<td><asp:Label ID=”VendorCityLabel” runat=”server” Text='<%# Eval(“VendorCity”) %>’ /></td>

<td><asp:Label ID=”VendorStateLabel” runat=”server” Text='<%# Eval(“VendorState”) %>’ /></td>

<td><asp:Label ID=”VendorCountryLabel” runat=”server” Text='<%# Eval(“VendorCountry”) %>’ /></td>

<td><asp:Label ID=”PostedDateLabel” runat=”server” Text='<%# Eval(“PostedDate”) %>’ /></td>

<td><asp:Label ID=”VendorDescriptionLabel” runat=”server” Text='<%# Eval(“VendorDescription”) %>’ /></td>

<td><asp:LinkButton ID=”LinkButtonEdit” runat=”server”CommandName=”Edit”>Edit</asp:LinkButton></td>

</tr>

</ItemTemplate>

</asp:ListView>

image1Figure 1.

Data Paging –

If you want to add Paging you have to use the new DataPager control. This control is a free standing control and what’s nice about it is that you can put it anywhere on the page – it doesn’t have to be directly visually associated with the control it’s actually doing the paging.

<tr runat=”server”>

<td runat=”server” style=”text-align: center; background-color: #5D7B9D; font-family: Verdana, Arial, Helvetica, sans-serif;

color: #FFFFFF”>

<asp:DataPager ID=”DataPager1″ runat=”server”>

<Fields>

<asp:NextPreviousPagerField ButtonType=”Button” ShowFirstPageButton=”True”ShowLastPageButton=”True” />

</Fields>

</asp:DataPager>

</td>

</tr>

image2

Figure 2.

Add, Edit and Delete:

The ListView also supports editing and adding of data via the EditItemTemplate and InsertItemTemplate. This functionality works very similar to the way it works in a GridView for editing, but it’s all done with custom templates:

This is .aspx code.

SQLDataSource :

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:VendorConnectionString %>”

SelectCommand=”SELECT [VendorId], [VendorFName], [VendorLName], [VendorCity], [VendorState], [VendorCountry], [PostedDate], [VendorDescription] FROM [Vendor]”>

</asp:SqlDataSource>

ListView :

<asp:ListView ID=”VendorListView” runat=”server” DataKeyNames=”VendorId”

DataSourceID=”SqlDataSource1″ onitemcommand=”VendorListView_ItemCommand”

onsorting=”VendorListView_Sorting” InsertItemPosition=”LastItem”>

<InsertItemTemplate>

<tr style=””>

<td></td>

<td><asp:TextBox ID=”TextBoxFName” Width=”100″ runat=”server” Text='<%# Bind(“VendorFName”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxLName” Width=”100″  runat=”server” Text='<%# Bind(“VendorLName”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxCity” Width=”100″  runat=”server” Text='<%# Bind(“VendorCity”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxState” Width=”100″  runat=”server” Text='<%# Bind(“VendorState”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxCountry” Width=”100″  runat=”server” Text='<%# Bind(“VendorCountry”) %>’ /></td>

<td></td>

<td><asp:TextBox ID=”TextBoxDescription” Width=”150″ TextMode=”MultiLine”runat=”server” Text='<%# Bind(“VendorDescription”) %>’ /></td>

<td><asp:Button ID=”ButtonInsert” runat=”server” CommandName=”Insert”Text=”Insert” /></td>

</tr>

</InsertItemTemplate>

<EditItemTemplate>

<tr style=”background-color: #999999;”>

<td><asp:TextBox ID=”TextBoxVendorId” Width=”100″   runat=”server” Text='<%# Bind(“VendorId”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxFName” Width=”100″  runat=”server” Text='<%# Bind(“VendorFName”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxLName” Width=”100″  runat=”server” Text='<%# Bind(“VendorLName”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxCity” Width=”100″  runat=”server” Text='<%# Bind(“VendorCity”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxState” Width=”100″  runat=”server” Text='<%# Bind(“VendorState”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxCountry” Width=”100″  runat=”server” Text='<%# Bind(“VendorCountry”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxPostedDate”  Width=”100″ runat=”server” Text='<%# Bind(“PostedDate”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxDescription” TextMode=”MultiLine”  Width=”150″ runat=”server” Text='<%# Bind(“VendorDescription”) %>’ /></td>

<td>

<asp:LinkButton ID=”LinkButtonUpdate” runat=”server”CommandName=”Update”>Update</asp:LinkButton>

<asp:LinkButton ID=”LinkButtonDelete” runat=”server”CommandName=”Delete”>Delete</asp:LinkButton>

<asp:LinkButton ID=”LinkButtonCancel” runat=”server”CommandName=”Cancel”>Cancel</asp:LinkButton>

</td>

</tr>

</EditItemTemplate>

</asp:ListView>

.CS Code:

protected void VendorListView_ItemCommand(object sender, ListViewCommandEventArgs e)

{

if (e.CommandName == “Insert”)

{

TextBox TextBoxFName = (TextBox)e.Item.FindControl(“TextBoxFName”);

TextBox TextBoxLName = (TextBox)e.Item.FindControl(“TextBoxLName”);

TextBox TextBoxCity = (TextBox)e.Item.FindControl(“TextBoxCity”);

TextBox TextBoxState = (TextBox)e.Item.FindControl(“TextBoxState”);

TextBox TextBoxCountry = (TextBox)e.Item.FindControl(“TextBoxCountry”);

TextBox TextBoxDescription = (TextBox)e.Item.FindControl(“TextBoxDescription”);

string insertCommand = “INSERT INTO Vendor ([VendorFName],[VendorLName],[VendorCity],[VendorState],[VendorCountry], [VendorDescription]) VALUES(‘” + TextBoxFName.Text + “‘, ‘” + TextBoxLName.Text + “‘, ‘” + TextBoxCity.Text +”‘, ‘” + TextBoxState.Text + “‘, ‘” + TextBoxCountry.Text + “‘, ‘” + TextBoxDescription.Text + “‘);”;

SqlDataSource1.InsertCommand = insertCommand;

}

else if (e.CommandName == “Update”)

{

TextBox TextBoxVendorId = (TextBox)e.Item.FindControl(“TextBoxVendorId”);

TextBox TextBoxFName = (TextBox)e.Item.FindControl(“TextBoxFName”);

TextBox TextBoxLName = (TextBox)e.Item.FindControl(“TextBoxLName”);

TextBox TextBoxCity = (TextBox)e.Item.FindControl(“TextBoxCity”);

TextBox TextBoxState = (TextBox)e.Item.FindControl(“TextBoxState”);

TextBox TextBoxCountry = (TextBox)e.Item.FindControl(“TextBoxCountry”);

TextBox TextBoxPostedDate = (TextBox)e.Item.FindControl(“TextBoxPostedDate”);

TextBox TextBoxDescription = (TextBox)e.Item.FindControl(“TextBoxDescription”);

string updateCommand = “UPDATE [Vendor] set [VendorFName]='” + TextBoxFName.Text + “‘, [VendorLName]='” + TextBoxLName.Text + “‘, [VendorCity]='” + TextBoxCity.Text + “‘, [VendorState]='” + TextBoxState.Text + “‘, [VendorCountry]='” + TextBoxCountry.Text + “‘, [PostedDate] = ‘” + TextBoxPostedDate.Text + “‘, [VendorDescription] = ‘” + TextBoxDescription.Text + “‘ WHERE VendorId=” +Convert.ToInt32(TextBoxVendorId.Text) + “;”;

SqlDataSource1.UpdateCommand = updateCommand;

}

else if (e.CommandName == “Delete”)

{

TextBox TextBoxVendorId = (TextBox)e.Item.FindControl(“TextBoxVendorId”);

string deleteCommand = “DELETE FROM [Vendor] WHERE VendorId=” +Convert.ToInt32(TextBoxVendorId.Text);

SqlDataSource1.DeleteCommand = deleteCommand;

}

}

image3

Figure 3.

image4

Figure 4.

image5

Figure 5.

 

 

 

 

AutoComplete in ASP.NET using Ajax

Introduction:

AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control, and will associate that control with a popup DropDown like list of words that begin with the prefix typed into the textbox.

Create a new website using ASP.NET Ajax-Enabled Web Site:
Now drag and drop three controls on page. ScriptManager, Textbox, AutoCompleteExtender.

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″%>

<form id=”form1″ runat=”server”>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />

<div>

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

<cc1:AutoCompleteExtender ID=”AutoCompleteExtender1″

runat=”server”

ServicePath=”WebService.asmx”

ServiceMethod=”FindName”

MinimumPrefixLength=”1″

TargetControlID=”TextBox1″>

</cc1:AutoCompleteExtender>

</div>

</form>

Now add a new WebService class:
Here is web service code.

Imports System

Imports System.Collections.Generic

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports System.Data.SqlClient

Imports System.Data

Imports System.Data.Common

Imports AtlasTextBoxAutoComplete.DL

Imports System.Collections

<WebService(Namespace:=”http://tempuri.org/&#8221;)> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<System.Web.Script.Services.ScriptService()> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

Public Class WebService

Inherits System.Web.Services.WebService

<WebMethod()> _

<System.Web.Script.Services.ScriptMethod()> _

Public Function FindName(ByVal prefixText As String, ByVal count As Integer) As String()

‘return all records whose Title starts with the prefix input string

Dim titleArList As New List(Of String)()

Dim drProducts As SqlDataReader = sqlProductProvider.GetNameList(prefixText)

While drProducts.Read()

Dim strTemp As String = Convert.ToString(drProducts(“Name”))

titleArList.Add(strTemp)

End While

Return titleArList.ToArray()

End Function

End Class

Result will look like this:


I am adding two classes in App_Code folder for database connectivity. You shoudl change your web.config key for database connection string. I am attaching my database in App_Code folder.

AJAX DragPanelExtender Control

Using DragPanel control, you can move your panel one place to another place in a Web page on client site. the web page. The DragPanelEtender control allows you to add drag and drop feature to your controls.

Here are two commong properties of

1 – TargetControlID – The ID of that Panel which should be drag.

2 – DragHandleID – The ID of a control that will serve as the “drag handle” for the panel. When the user clicks and drags this control, the panel will move.

.aspx code

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit”TagPrefix=”cc1″ %>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />

<br />

<cc1:DragPanelExtender ID=”DragPanelExtender1″

runat=”server” TargetControlID=”PanelContainer”

DragHandleID=”PanelBody”>

</cc1:DragPanelExtender>

<div>

<asp:Panel ID=”PanelContainer” runat=”server”CssClass=”dragContainer” Width=”215px” >

<asp:Panel ID=”PanelBody” runat=”server” CssClass=”dragBody”Width=”215px”>

<asp:GridView ID=”GridView1″ runat=”server”

AutoGenerateColumns=”False” DataSourceID=”SqlDataSource1″

AllowPaging=”True” PageSize=”7″ CellPadding=”4″ForeColor=”#333333″

GridLines=”None” Width=”215px”>

<Columns>

<asp:BoundField DataField=”ContactName”HeaderText=”ContactName” SortExpression=”ContactName” />

</Columns>

<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True”ForeColor=”White” />

<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />

<EditRowStyle BackColor=”#999999″ />

<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True”ForeColor=”#333333″ />

<PagerStyle BackColor=”#284775″ ForeColor=”White”HorizontalAlign=”Center” />

<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True”ForeColor=”White” />

<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″/>

</asp:GridView>

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”ConnectionString=”<%$ ConnectionStrings:C:\USERS\MAHESH\DESKTOP\AUTOCOMPLETE_SRC\ATLASTEXTBOXAUTOCOMPLETE\APP_DATA\NORTHWND.MDFConnectionString%>”

SelectCommand=”SELECT [CompanyName], [ContactName], [Address], [City], [Country] FROM [Customers]”>

</asp:SqlDataSource>

</asp:Panel>

</asp:Panel>

</div>

</form>

<script type=”text/javascript”>

function setBodyHeightToContentHeight() {

document.body.style.height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)+”px”;

}

setBodyHeightToContentHeight();

window.attachEvent(‘onresize’, setBodyHeightToContentHeight);

</script>

NOTE: In the above code, make sure to change your connection string.

Caching in ASP.NET 2.0

Introduction

Caching is a technique of storing a copy of data in memory. For example, you may cache the a page or the results of a query. The advantage of caching is to build better performance into your application. Accessing cached data in memory is much faster than re-building a page or re-querying the database.

There are two types of caching in asp.net 2.0:

  1. Output Caching
  2. Data Caching
  1. Output Caching

    Output caching stores an HTML page in a cache that will not refresh until your specified duration time passes.

    <%@ OutputCache Duration=”30″ VaryByParam=”None” %>.

    Duration -> Allows you to specify time in seconds.

    VaryByParam -> Output based on query string.

    <%@ OutputCache Duration=”30″ VaryByParam=”UserID” %>.

    Result
    1


    The date/time will refresh automatically after 30 seconds if you put the following code on a page load event.

protected void Page_Load(object sender, EventArgs e)
{

LabelDate.Font.Bold = true;

LabelDate.Font.Italic = true;

LabelDate.Text = “The DateTime is now:<br/>”;

LabelDate.Text += DateTime.Now.ToString();
}

Put this line on top of your .aspx page and set your duration time as desired.

<%@ OutputCache Duration=”30″ VaryByParam=”None” %>.

  1. Data Caching

    Data caching is the most important type of caching. The basic principle of data caching is that you can add items in your collection object called Cache.

Example

protected void Page_Load(object sender, EventArgs e)

{

LabelData.Font.Bold = true;

LabelData.Font.Italic = true;

if (Cache[“RajCacheItems”] == null)

{

LabelData.Text += “Raj creating items…..<br />”;

DateTime dateTime = DateTime.Now;

LabelData.Text += “Storing items in cache “;

LabelData.Text += “for 50 seconds.<br />”;

Cache.Insert(“RajCacheItems”, dateTime, null, DateTime.Now.AddSeconds(50),TimeSpan.Zero);

}

else

{

LabelData.Text += “Accessing RajCacheItems…..<br />”;

DateTime dateTime = (DateTime)Cache[“RajCacheItems”];

LabelData.Text += “RajCacheItems is ‘” + dateTime.ToString();

}

}

Result

2



Data Source Control Caching

This is the caching that is built into the data source controls like SqlDataSource, ObjectDataSource and XmlDataSource.

There are four properties of caching in SqlDataSource:

  1. Enable Caching: You need to set the enable caching property to true; the default value is false.
  2. Cache Expiration Policy: Absolute and sliding.
  3. Cache Duration: Duration time in seconds.
  4. CacheKeyDependency: Makes a cached item dependent on another item in the data cache or on a table in your database.

Example

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:TestConnectionString %>”

SelectCommand=”SELECT [Id], [FirstName], [LastName], [Address], [City], [State], [Country] FROM [Records] WHERE ([City] = @City)”

EnableCaching=”True” CacheExpirationPolicy=”Sliding” CacheDuration=”20″>
<SelectParameters>

<asp:ControlParameter ControlID=”DropDownList1″ Name=”City” PropertyName=”SelectedValue”Type=”String” />

</SelectParameters>

</asp:SqlDataSource>

Result
3