DetailsView Rich Data Control

Introduction:

In this article we are going to discuss about DetailsView data control.  In ASP.NET 2.0, DetailsView is a data-bound control that renders a single record at a time from its associated data source. It can optionally provide paging buttons to navigate between records, and a command bar to execute basic operations on the current record (Insert, Update, Delete). DetailsView generates a user interface similar to the Form View of a Microsoft Access database, and is typically used for updating/deleting any currently displayed record or for inserting new records.  The difference between the DetailsView and FormView is their support for templates. The DetailsView is build out of field objects, in the same way that the Grid View is build out of column objects.

You can configure the DetailsView control to display a Delete and an Insert button so that you can delete the corresponding data record from the data source or insert a new data record. Similar to the AutoGenerateInsertButton property, when the  AutoGenerateInsertButton property is set to true on the DetaillsView control, it renders a New button. When the New button is clicked, the DetaillsView control’s CurrentMode property changes to Insert. The DetaillsView control renders appropriate UI input controls for each bound field, unless the InsertVisible property of the bound field is set to false.

I am going to show use of all command bar in details.

NOTE I am using northwind database for this sample.

1

Figure 1: is showing one records at a time and paging is enabled.

2

Figure 2: when click on new command bar then should be look like this. Here you can insert record in database.

3

Figure 3: You can update existing record using update command bar.

So don’t you think it’s very useful control. I did not write one like code during insert, delete, update. For more information I am writing .aspx page code and attaching my sample application you need to only change connection string in web.config. And I am using SqlDataSource. You can use whatever you want according to your need.

. aspx code

DetailsView:

<asp:DetailsView ID=”DetailsView1″ runat=”server” Height=”50px”

Width=”532px” AllowPaging=”True” AutoGenerateRows=”False”

CellPadding=”4″ DataKeyNames=”EmployeeID” DataSourceID=”SqlDataSource1″

ForeColor=”#333333″ GridLines=”None” AutoGenerateDeleteButton=”True”

AutoGenerateEditButton=”True” AutoGenerateInsertButton=”True”>

<FooterStyle BackColor=”#990000″ Font-Bold=”True” ForeColor=”White” />

<CommandRowStyle BackColor=”#FFFFC0″ Font-Bold=”True” />

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

<PagerStyle BackColor=”#FFCC66″ Font-Names=”Georgia” Font-Size=”Medium”ForeColor=”#333333″

HorizontalAlign=”Center” />

<Fields>

<asp:BoundField DataField=”EmployeeID” HeaderText=”EmployeeID”InsertVisible=”False” ReadOnly=”True” SortExpression=”EmployeeID” />

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

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

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

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

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

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

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

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

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

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

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

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

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

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

</Fields>

<FieldHeaderStyle BackColor=”#FFFF99″ Font-Bold=”True” />

<HeaderStyle BackColor=”#990000″ Font-Bold=”True” Font-Names=”Georgia”ForeColor=”White” />

<AlternatingRowStyle BackColor=”White” />

<EditRowStyle Font-Names=”Georgia” Font-Size=”Small” />

</asp:DetailsView>

SqlDataSource:

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

SelectCommand=”SELECT * FROM [Employees] ORDER BY [EmployeeID]”

DeleteCommand=”DELETE FROM [Employees] WHERE EmployeeID = @EmployeeID”

InsertCommand = “INSERT INTO [Employees] ([LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City],[Region], [PostalCode], [Country], [HomePhone], [Extension], [Notes]) VALUES (@LastName, @FirstName, @Title, @TitleOfCourtesy, @BirthDate, @HireDate, @Address, @City, @Region, @PostalCode, @Country, @HomePhone, @Extension, @Notes)”

UpdateCommand = “UPDATE [Employees] SET [LastName] = @LastName, [FirstName] = @FirstName, [Title] = @Title, [TitleOfCourtesy] = @TitleOfCourtesy, [BirthDate] = @BirthDate, [HireDate] = @HireDate,[Address] = @Address, [City] = @City, [Region] = @Region, [PostalCode] = @PostalCode, [Country] = @Country, [HomePhone] = @HomePhone, [Extension] = @Extension, [Notes] = @Notes  WHERE [EmployeeID] = @EmployeeID”>

<DeleteParameters>

<asp:Parameter Name=”EmployeeID” Type=”int32″  />

</DeleteParameters>

<InsertParameters>

<asp:Parameter Name=”LastName” Type=”String”  />

<asp:Parameter Name=”FirstName” Type=”String”  />

<asp:Parameter Name=”Title” Type=”String”  />

<asp:Parameter Name=”TitleOfCourtesy” Type=”String”  />

<asp:Parameter Name=”BirthDate” Type=”datetime”  />

<asp:Parameter Name=”HireDate” Type=”datetime”  />

<asp:Parameter Name=”Address” Type=”String”  />

<asp:Parameter Name=”City” Type=”String”  />

<asp:Parameter Name=”Region” Type=”String”  />

<asp:Parameter Name=”PostalCode” Type=”String”  />

<asp:Parameter Name=”Country” Type=”String”  />

<asp:Parameter Name=”HomePhone” Type=”String”  />

<asp:Parameter Name=”Extension” Type=”String”  />

<asp:Parameter Name=”Notes” Type=”String”  />

<asp:Parameter Name=”ReportsTo” Type=”int32″  />

<asp:Parameter Name=”PhotoPath” Type=”String”  />

</InsertParameters>

<UpdateParameters>

<asp:Parameter Name=”EmployeeID” Type=”int32″  />

<asp:Parameter Name=”LastName” Type=”String”  />

<asp:Parameter Name=”FirstName” Type=”String”  />

<asp:Parameter Name=”Title” Type=”String”  />

<asp:Parameter Name=”TitleOfCourtesy” Type=”String”  />

<asp:Parameter Name=”BirthDate” Type=”datetime”  />

<asp:Parameter Name=”HireDate” Type=”datetime”  />

<asp:Parameter Name=”Address” Type=”String”  />

<asp:Parameter Name=”City” Type=”String”  />

<asp:Parameter Name=”Region” Type=”String”  />

<asp:Parameter Name=”PostalCode” Type=”String”  />

<asp:Parameter Name=”Country” Type=”String”  />

<asp:Parameter Name=”HomePhone” Type=”String”  />

<asp:Parameter Name=”Extension” Type=”String”  />

<asp:Parameter Name=”Notes” Type=”String”  />

<asp:Parameter Name=”ReportsTo” Type=”int32″  />

<asp:Parameter Name=”PhotoPath” Type=”String”  />

</UpdateParameters>

</asp:SqlDataSource>

So what are you waiting for just implement this control.

Ajax AnimationExtender Control

In this article we are going to discuss about AJAX AnimationExtender control.

If you want to use animation to the web pages, then you have to use AnimationExtender control. It provides good animation effect such as moving an ASP Control to a new place, resizing it, modifying its color, or making it fade in or fade out. In this article I m going to use fade in or fade out animation.

The animation behavior can be applied with the following extender (the italic properties are optional, and the ellipses represent a generic animation description

TargetControlID: ID of the target control whose events are used to animate (this is also the default target of the animations)

OnLoad: Generic animation played as soon as the page is loaded.

OnClick: Generic animation played when the target control is clicked.

OnMouseOver: Generic animation played when the mouse moves over the target control.

OnMouseOut: Generic animation played when the mouse moves out of the target control.

OnHoverOver: Generic animation similar to OnMouseOver except it will stop the OnHoverOut animation before it plays.

OnHoverOut: Generic animation similar to OnMouseOut except it will stop the OnHoverOver animation before it plays.

First of all make a new website using Ajax Enabled website. The advantage to using Ajax enabled website is no need to add ScriptManager control on page and no need to add Ajax Control toolkit. Like this:

First of all drag and drop Animation control on page.

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

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
<cc1:AnimationExtender ID=”AnimationExtender1″ runat=”server” TargetControlID=”Image1″>
<Animations>
<OnLoad>
<FadeOut Duration=”.5″ MinimumOpacity=”.2″ MaximumOpacity=”1″ />
</OnLoad>
<OnHoverOut>
<Sequence>
<FadeOut Duration=”.5″ MinimumOpacity=”.2″ MaximumOpacity=”1″ />
</Sequence>
</OnHoverOut>
<OnHoverOver>
<FadeIn Duration=”.5″ MinimumOpacity=”.2″ MaximumOpacity=”1″ />
</OnHoverOver>
</Animations>
</cc1:AnimationExtender>
<asp:Image runat=”server” ID=”Image1″ ImageUrl=”~/Sunset.jpg” BorderWidth=”0px”Width=”342px” />

After running result should be look like this:



Now check result on MouseHover on this picture. Result should be look like this:

Database Connectivity using WebService

Introduction:

This article shows how to use Web Service and how to get data from database using Web Service. The Web Service behavior enables a client-side script to invoke remote methods exposed by Web Services or other web servers that support the SOAP and Web Services Description Language (WSDL) 1.1. This behavior provides developers the opportunity to use and leverage SOAP without requiring expert knowledge of its implementation. The Web Service behavior supports the use of a wide variety of data types, including intrinsic SOAP data types, arrays, objects and XML data.

Web Services have Two Uses:

Reusable application components
Web Services can offer application components as services such as currency conversion, weather reports or even language translation.

Ideally, there will only be one type of each application component, and anyone can use it in his or her application.

Connect existing software

Web Services help solve the interoperability problem by giving different applications a way to link their data.

Using Web Services you can exchange data between different applications and different platforms.

Let’s starts now by adding a new class in your application (Web Service) using the following information:

1

I am using default a database in my application; you can use whatever data you want to use. Put this web method in your web service class. I am using the Northwind database and customer table.

[WebMethod(Description = “Get all customers from customer table”)]

public DataSet GetLatestCustomers()

{
using (SqlConnection connection = new SqlConnection
(ConfigurationManager.ConnectionString”dataConnectionString”].ConnectionString))

{
string Query = “SELECT * FROM [Customers] ORDER BY [CustomerID] DESC”;

SqlCommand command = new SqlCommand(Query, connection);

command.CommandType = CommandType.Text;

connection.Open();

SqlDataReader reader = command.ExecuteReader();

DataTable myTable = new DataTable(“myTable”);

myTable.Columns.Add(“CustomerID”, typeof(string));

myTable.Columns.Add(“CompanyName”, typeof(string));

myTable.Columns.Add(“ContactName”, typeof(string));

myTable.Columns.Add(“ContactTitle”, typeof(string));

myTable.Columns.Add(“Address”, typeof(string));

myTable.Columns.Add(“City”, typeof(string));

myTable.Columns.Add(“Region”, typeof(string));

myTable.Columns.Add(“PostalCode”, typeof(string));

myTable.Columns.Add(“Country”, typeof(string));

myTable.Columns.Add(“Phone”, typeof(string));

myTable.Columns.Add(“Fax”, typeof(string));

while (reader.Read())

{
myTable.Rows.Add(new object[]

{

reader[“CustomerID”].ToString(), reader[“CompanyName”].ToString(),
reader[“ContactName”].ToString(), reader[“ContactTitle”], reader
[“Address”], reader[“City”], reader[“Region”], reader[“PostalCode”],
reader[“Country”],reader[“Phone”], reader[“Fax”] });

}

//myTable.Load(reader);

myTable.AcceptChanges();

DataSet ds = new DataSet();

ds.Tables.Add(myTable);

ds.AcceptChanges();

return ds;

}
}

Put your class in the App_Code folder. I am using a GridView control to show data on the page.

Now make an object to call your class like this:

Service service = new Service();

And put these two lines of code on the page load event.

GridView1.DataSource = service.GetLatestCustomers();
GridView1.DataBind();

@2

That’s it.

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

Message window using VB.NET in ajax

This article is used to show message window in vb.net using ajax. The problem comes when you use vb.net using ajax enables website.. This concept is easy to use in C# but it is not easy in vb.net. I am writing two line code for this message window.

Private Sub DisplayClientError(ByVal errorDesc As String)
Dim script As String = “alert(‘” + errorDesc + “‘);”
ScriptManager.RegisterStartupScript(Me, GetType(Page), “UserSecurity”, script, True)
End Sub ‘DisplayClientError write this code on click event where you want show message window
Protected Sub ClickButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlesClickButton.Click
If TextBox1.Text = “” Then
DisplayClientError(“Enter some text in text box”)
End If
End Sub

Screenshot:

Data Binding in WPF ListView

In this article, I am going to explain how to extract data from database and how to show data on a page using WPF ListView control.

I am using Northwind database, you can use whatever you want, and only you have to change is the connection string, your SQL string, and the binding properties in XAML code.

Here is the. xaml code:

<Grid x:Name=”Grid1″>

<ListView Name=”ListViewEmployeeDetails” Margin=”4,20,40,100″ ItemTemplate=”{DynamicResource EmployeeTemplate}” ItemsSource=”{Binding Path=Table}”>

<ListView.Background>

<LinearGradientBrush>

<GradientStop Color=”Gray” Offset=”0″/>

</LinearGradientBrush>

</ListView.Background>

<ListView.View>

<GridView>

<GridViewColumn Header=”Employee ID” DisplayMemberBinding=”{Binding Path=EmployeeID}”/>

<GridViewColumn Header=”First Name” DisplayMemberBinding=”{Binding Path=FirstName}”/>

<GridViewColumn Header=”Last Name” DisplayMemberBinding=”{Binding Path=LastName}”/>

<GridViewColumn Header=”BirthDate” DisplayMemberBinding=”{Binding Path=BirthDate}”/>

<GridViewColumn Header=”City” DisplayMemberBinding=”{Binding Path=City}”/>

<GridViewColumn Header=”Country” DisplayMemberBinding=”{Binding Path=Country}”/>

</GridView>

</ListView.View>

</ListView>

</Grid>

Here is .cs code:

SqlConnection con = new SqlConnection();

SqlDataAdapter ad = new SqlDataAdapter();

SqlCommand cmd = new SqlCommand();

String str = “SELECT EmployeeID, FirstName, LastName, BirthDate, City, Country FROM Employees”;

cmd.CommandText = str;

ad.SelectCommand = cmd;

con.ConnectionString = “Data Source=localhost; Initial Catalog=Northwind; Integrated Security=True”;

cmd.Connection = con;

DataSet ds = new DataSet();

ad.Fill(ds);

ListViewEmployeeDetails.DataContext = ds.Tables[0].DefaultView;

con.Close(); 

Note:  Add two namespace.

using System.Data.SqlClient;
using System.Data; 

Snapshot:

Ajax Always Visible Control Extender

In this article I am going to discuss an Ajax control named ‘AlwaysVisibleControlExtender’ and how to use it in ASP.Net 2.0.

AlwaysVisibleControlExtender is used to define area of content on user interface to remain visible no matter how the user scrolls around the rest of the content of the page. The AlwaysVisibleControl is a simple extender allowing you to pin controls to the page so that they appear to float over the background body content when it is scrolled or resized. It targets any ASP.NET control and always keeps the position a specified distance from the desired horizontal and vertical sides. I am using a panel that will be visible all the time when you will scroll page.

Ok let’s start from beginning, first of all Open Microsoft Visual Studio2005 and create a new website in ASP.NET Enabled Website.

SnapShot 1:

There should be already a control named ScriptManager. Now add AjaxControl Toolkit in your Bin directory. Drag and drop a Panel control on page, and put all contents which you want to be visible all the time on the page; it doesn’t matter whether the page is scrolling or not. Now drag and drop AlwaysVisibleControlExtender control from Toolbox and set TargetControlID to that PanelID. For testing whether it’s working or not, put lots of contents on your page.

Here is .aspx code:
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />

<asp:Panel ID=”Panel1″ BorderStyle=solid BorderWidth=2 runat=”server” Height=”100px”Width=”200px”    BackColor=yellow BorderColor=red>

<p>

<span style=”font-size: 10pt; font-family: Tahoma”>

<strong>Message:</strong>

</span>

</p>

<div>

<span style=”font-size: 10pt”>

<span style=”font-family: Tahoma”>

This Panel will visible all the time when you will scroll the page.

</span>

</span>

</div>

<p>

<span style=”font-size: 10pt”>

<strong>

<span style=”font-family: Verdana”>Current Time:

</span>

</strong>

</span>

<asp:Label ID=”Label1″ runat=”server” Font-Bold=”True” Font-Names=”Verdana” Font-Size=”10pt”>

</asp:Label>

</p>

</asp:Panel>

<div>

<cc1:alwaysvisiblecontrolextender ScrollEffectDuration=”.1″ HorizontalSide=RightHorizontalOffset=10
VerticalSide=”Middle” VerticalOffset=”10″ TargetControlID=”Panel1″

id=”AlwaysVisibleControlExtender1″ runat=”server”>

</cc1:alwaysvisiblecontrolextender>

</div>

Snapshot 2: