Friday, November 13, 2009

Using LINQ to query object hierarchies

I used LINQ to solve the following problem: find all titles of objects at hierarchy level X when you know object ID in hierarchy level Y. I cannot imagine if there is some other solution that is same short and clear as one that LINQ provides. Take a look and decide by yourself.
linq-levels-example Here is simple diagram with my entities. Here are my simple rules. Level1 has no parent level and my contain one ore more Level2 entities. Level2 entities have one Level1 parent and one or more Level3 enitities. Level3 entities have one Level2 parent entity and collection of one or more Items. So there is many-to-many relationship between Level3 and Items.
We cannot use composite pattern here because these classes will be very different and there will be no point where we need one common interface for them. That’s why we have one class per level. Also the number of levels is fixed and there is no plan to expand this hierarchy.
By the way, you can model arbitrary class hierarchies on this model and still use this example (as long as it doesn’t hurt performance and you are really sure what you are doing).
Excercise: having Level1 items collection and knowing Level3 item ID find all Items for specified Level3 item and return string of their titles separated by comma. As you don’t have access to source code of data source you must use IList<Level1> and LINQ.
We will use simple class structure given below and we expect that we already got list of Level1 items from some repository or data context.

public class Level1
{
    public int Id { get; set; }
    public string Title { get; set; }
    public IList<Level2> Level2Items { get; set; }
}

public class Level2
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Level1 Parent { get; set; }
    public IList<Level3> Level3Items { get; set; }
}

public class Level3
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Level2 Parent { get; set; }
    public IList<Item> Items { get; set; }
}

public class Item
{
    public int Id { get; set; }
    public string Title { get; set; }
}

Now it’s time to write some hardcore loops and create a cool code-hell… or maybe it’s time to be elegant and use LINQ as stated before. Using LINQ we can provide the following solution:

public string GetItemsStringForLevel3(IList<Level1> level1Items, int level3Id)
{           
    var items = from l in level1Items
                  from l2 in l.Level2Items
                  from l3 in l2.Level3Items
                  from p in l3.Items
                where l3.Id == level3Id
                select p.Title;

    return string.Join(", ", items.ToArray());
}

--
Happy Programming

jQuery for Absolute Beginners: The Complete Video Series

A great VIDEO series on all the nice effects (and functionality) you can achieve with jQuery JavaScript library for those who know NOTHING about it.
jQuery is a very powerful library. One of the first things I do when creating new project is to include the library in it. Microsoft is going to include it by default in ASP.NET web projects (All ASP.Net projects, not just MVC) starting Visual Studio 2010.
Here are some few examples of what you can do with it (VIDEO):

http://net.tutsplus.com/articles/web-roundups/jquery-for-absolute-beginners-video-series/?awesm=fbshare.me_EIez#



---
Happy Programming

Thursday, November 12, 2009

Statement cannot appear within a method body. End of method assumed

Today when I was developing web pages using asp.net,I encountered a problem as below:
Server Error in '/BC30289' Application.
 
Compilation Error Description:
An error occurred during the compilation of a resource required to service  this request. Please review the following specific error details and modify your  source code appropriately.

Compiler Error Message: 
BC30289:  Statement cannot appear within a method body. End of method assumed.

Error Line: Sub showImage(Byval id as string)
I replaced "<% %>" with
<script language="vbscript" runat="server"></script>

And then everything works fine.

That is because we cannot define asp 'sub' or 'function' between the body tag

--
Happy Programming

Use Output clause in Delete Statement in sqlserver 2005

Here i give simple example of delete statement with output clause.
if you want track the deleted row information at that time generally
we preffered trigger right?
here we inserte the deleted row in the other history table. we create
the two talbe one is data table and other for history purpose.
1) Create Table (Name:Table_1)
GO
CREATE TABLE [dbo].[Table_1]

( [id] [int] IDENTITY(1,1) NOT NULL,
[code] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]

2) Create Table For Save Deleted Record in other table (DeletedTblInfo)
GO
CREATE TABLE [dbo].[DeletedTblInfo]
( [DeletedTableInfoId] [int] IDENTITY(1,1) NOT NULL,

[DeletedTableId] [int] NULL,
[DeletedRowId] [int] NULL,
 [DeletedDateTime] [datetime] NULL,
CONSTRAINT [PK_DeletedTblInfo] PRIMARY KEY CLUSTERED ( [DeletedTableInfoId] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]

3) insert data into data table
go
INSERT INTO Table_1
 (code)
VALUES
(‘test1′)

 go
INSERT INTO Table_1
 (code)
 VALUES
(‘test2′)
go

INSERT INTO Table_1
(code)
VALUES
(‘test3′)
go
INSERT INTO Table_1

(code)
VALUES
(‘test4′)
4) now delete from table 1 where id =4
–here the record save in the DeletedTblInfo
–DeletedTableId : the table id where data is deleted or the table name if you want then.
–DeletedRowId : deleted RowId

–DeletedDateTime : deleted DateTime
DELETE FROM Table_1
OUTPUT 1,DELETED.ID,getdate()
INTO DeletedTblInfo WHERE (Id = 4);

–now see the result in the history table
DeletedTableInfoId
DeletedTableId
DeletedRowId
DeletedDateTime
1
1
4
5/7/2008 12:53:52 PM

What is Maximum Request size for asp.net application?

The default max request size is 4MB (4096).
You can change a setting in your web.config to allow larger requests.
Here is the example:
   1: <configuration>
   2:        <system.web>

   3:            <httpRuntime  maxRequestLength="4096"/>
   4:        </system.web>

   5: </configuration>
This is default setting, we have to change this to the size that you want to allow user to request like 10MB, 20MB…

---
Happy Programming

Saturday, November 7, 2009

Multiple File Upload using JQuery

Introduction

In this article I have explained how to upload multiple files using file upload control. I have used jQuery plugin for uploading multiple files.

I have also explained how to check for file type, file maximum size limit using jQuery & also using server side validation code.
Download the Following Files



Namespace used

using System.Security.Cryptography;
using System.Text;
using System.IO;

Step 1: Include the jQuery Files needed on the page.

Assuming you have downloaded these files, create a reference to these files in the <head> section of your page as shown below:

<head id="Head1" runat="server">
<title>Multiple File Upload using JQuery</title>
<script src="Scripts/jquery-1.3.2.js"
type="text/javascript">
</script>
<script src="Scripts/jquery.MultiFile.js"
type="text/javascript">
</script>
</head>

Step 2: Add File Upload Control & Button on the Page.

<asp:FileUpload ID="FileUpload1" runat="server"
accept="gif|jpeg|bmp|png|jpg"
maxlength="5" />
<br />
<asp:Button ID="btnUpload" runat="server"
Text="Upload All" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblMsg" runat="server" Text="">\
</asp:Label>
class=”multi” is used to specify that user can select multiple files.

maxlength property specify that user can upload maximum 5 files not more than that.

accept property used to restrict user to upload only certain type of file only.

Step 3: Double click on Upload Button & Write the code that is used to upload files.

protected void btnUpload_Click(object sender, EventArgs e)
{
if (ServerSideValidation() == true)
{
string SavePath, Msg = null;

// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString()
+ GetUniqueKey() + GetFileExtension(hpf.FileName);
hpf.SaveAs(Server.MapPath(SavePath));
//SavePath can be saved in DB.
Msg += GetFileName(hpf.FileName.ToString()) + " , ";
}
}
lblMsg.Text = Msg + " Uploaded Successfully.";
}
}


Step 4: Write the private function which helps to Upload files.

This function helps to extract file extension from the fileName.

private string GetFileExtension(string FileName)
{
char saperator = ‘.’;
string[] temp = FileName.Split(saperator);

return "." + temp[1].ToString();
}

This function helps to get Unique Key, which is used to save files on server with different name that does not collied with each other.

private string GetUniqueKey()
{
int maxSize = 8;
char[] chars = new char[62];
string a;

a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

chars = a.ToCharArray();

int size = maxSize;
byte[] data = new byte[1];

RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);

foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}

return result.ToString();
}

This function help to get Filename from the filepath.

private string GetFileName(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Name;
}


Step 5: Add Server Side Validation Code

This is the function which is used to validate files that user wants to upload. If the client side validation does not work, this code will help us to identify the invalid files.

Validation rules like whether file type is correct or not, file size is valid or not.

If you do not want to validate the files on server side, you can ignore this code. But I prefer to use it.

private bool ServerSideValidation()
{
string errorMsg = string.Empty , temp=null;
bool errorFlag = true;

// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
temp = ValidateImage(hpf);
if(temp != null)
{
errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
temp = null;
}
}
}

if (errorMsg != "")
{
lblMsg.Text = errorMsg;
errorFlag = false;
}
return errorFlag;
}

This function used to check file type & file size. If file is invalid than it will return error message.

private string ValidateImage(HttpPostedFile myFile)
{
string msg = null;     
int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
//Check Length of File is Valid or Not.
if (myFile.ContentLength > FileMaxSize)
{
msg = msg + "File Size is Too Large.";
}
//Check File Type is Valid or Not.     
if (!IsValidFile(myFile.FileName))
{                  
msg = msg + "Invalid File Type.";
}
return msg;
}

This function is used to check whether the file that user want to upload is valid file type or not.

private bool IsValidFile(string filePath)
{
bool isValid = false;

string[] fileExtensions = { ".bmp", ".jpg", ".png", ".gif", ".jpeg", ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };

for (int i = 0; i < fileExtensions.Length; i++)
{
if (filePath.Contains(fileExtensions[i]))
{
isValid = true;
}
}
return isValid;
}

Conclusion:

This code is complete solution that helps to upload multiple file using File Upload with jQuery plugin. I was always in a need of such code in my route work so I decided to write the code that helps others also.

Hope this will help !!!

Thursday, October 29, 2009

EXISTS or COUNT(*) Which Do You Use To Check How Many Rows There Are?

Do you use this

IF (SELECT COUNT(*) FROM SomeTable
WHERE SomeColumn = SomeValue ) > 0

Or do you use this

IF EXISTS (SELECT * FROM SomeTable WHERE SomeColumn = SomeValue )

If you answered COUNT(*) then maybe you should take a look these two articles

Andrew Kelly has a nice post on SQLBlog
http://sqlblog.com/blogs/andrew_kelly/archive/2007/12/15/exists-vs-count-the-battle-never-ends.aspx

Matija Lah has a good post on his snaps & snippets blog
http://milambda.blogspot.com/2006/10/exists-or-not-exists-that-is-question.html

Monday, October 26, 2009

DateTime String Format In Asp.net

Here are some of the string formats that you can try out:
Specifier
type
output
(June 8, 1970 12:30:59)
dd
Day
08
ddd
Short Day Name
Mon
dddd
Full Day Name
Monday
hh
2 digit hour
12
HH
2 digit hour (24 hour)
12
mm
2 digit minute
30
MM
Month
06
MMM
Short Month name
Jun
MMMM
Month name
June
ss
seconds
59
tt
AM/PM
PM
yy
2 digit year
70
yyyy
4 digit year
1970
:
seperator, e.g. {0:hh:mm:ss}
12:30:59
/
seperator, e.g. {0:dd/MM/yyyy}
08/06/1970

Try this way

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="CheckDateFormat" DataField="Date" DataFormatString="{0:M-dd-yyyy}" />
</Columns>
</asp:GridView>
---
DateTime dt = DateTime.Now;
String strDate="";
strDate = dt.ToString("MM/dd/yyyy");   // 07/21/2007 

strDate = dt.ToString("dddd, dd MMMM yyyy");   //Saturday, 21 July 2007

strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm"); // Saturday, 21 July 2007 14:58

strDate = dt.ToString("dddd, dd MMMM yyyy hh:mm tt"); // Saturday, 21 July 2007 03:00 PM

strDate = dt.ToString("dddd, dd MMMM yyyy H:mm"); // Saturday, 21 July 2007 5:01 

strDate = dt.ToString("dddd, dd MMMM yyyy h:mm tt"); // Saturday, 21 July 2007 3:03 PM

strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:04:10

strDate = dt.ToString("MM/dd/yyyy HH:mm"); // 07/21/2007 15:05

strDate = dt.ToString("MM/dd/yyyy hh:mm tt"); // 07/21/2007 03:06 PM

strDate = dt.ToString("MM/dd/yyyy H:mm"); // 07/21/2007 15:07

strDate = dt.ToString("MM/dd/yyyy h:mm tt"); // 07/21/2007 3:07 PM

strDate = dt.ToString("MM/dd/yyyy HH:mm:ss"); // 07/21/2007 15:09:29

strDate = dt.ToString("MMMM dd"); // July 21

strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"); // 2007-07-21T15:11:19.1250000+05:30    

strDate = dt.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"); // Sat, 21 Jul 2007 15:12:16 GMT

strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); // 2007-07-21T15:12:57

strDate = dt.ToString("HH:mm"); // 15:14

strDate = dt.ToString("hh:mm tt"); // 03:14 PM

strDate = dt.ToString("H:mm"); // 5:15

strDate = dt.ToString("h:mm tt"); // 3:16 PM

strDate = dt.ToString("HH:mm:ss"); // 15:16:29

strDate = dt.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'"); // 2007-07-21 15:17:20Z

strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:17:58

strDate = dt.ToString("yyyy MMMM"); // 2007 July




Hence we can format and getting the datetime value.

Saturday, October 24, 2009

Export DataSet or DataTable to Word, Excel, PDF and CSV Formats

using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
Function to get the results in datatable
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.
ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
As you can see above I am passing the query to the GetData function and it returns the results as datatable back.
Export to Word
protected void ExportToWord(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.doc”);
Response.Charset = “”;
Response.ContentType = “application/vnd.ms-word “;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
image
Export to Excel
Below is the code to export the datatable to Excel Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as Excel Workbook. Also you will notice I applied textmode style to all the rows so that it in rendered as text.
protected void ExportToExcel(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.xls”);
Response.Charset = “”;
Response.ContentType = “application/vnd.ms-excel”;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add(”class”, “textmode”);
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @””;
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
image1
Export to Portable Document Format (PDF)
Below is the code to export the datatable to PDF Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as PDF document using the iTextSharp Library which is a free open source library and can be downloaded from here.
protected void ExportToPDF(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.ContentType = “application/pdf”;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.pdf”);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
image2
Export to Comma Separated Values (CSV)
Below is the code to export the datatable to CSV or Text Format. It first fills the datatable using the GetData function. To export dataset to CSV there is no need of dummy GridView. We just have to loop through the records and append the delimiting character comma.
protected void ExportToCSV(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.csv”);
Response.Charset = “”;
Response.ContentType = “application/text”;
StringBuilder sb = new StringBuilder();
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(dt.Columns[k].ColumnName + ‘,’);
}
//append new line
sb.Append(”\r\n”);
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(dt.Rows[i][k].ToString().Replace(”,”, “;”) + ‘,’);
}
//append new line
sb.Append(”\r\n”);
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
image3

Master / Detail Editing With a ListView and DetailsView

mplementing a master/detail editing-inserting-deleting interface using the ListView is not much different than doing it with a GridView. Here's a quick tutorial that shows how it's done.
I'm sure you're all familiar with editing records in a master/detail scenario with a GridView and DetailsView. There are probably a thousand tutorials on the 'net that show how to do this. So, when I happened upon a fellow on the ASP.NET forums asking about doing master/detail editing with the ListView instead of the GridView , my first thought was to post a link and tell him to have at it. However, to my surprise, a quick Google search didn't really reveal any good, straightforward examples. That being the case, I decided to work one up, which I'll share with you now.
The ListView is a new databound control introduced with the .NET Framework 3.5. You could think of the ListView as what you might get if a GridView and a Repeater had a baby. Like the GridView, the ListView can display, edit, delete, page, and sort records. And like the Repeater, the ListView is entirely template-driven. Also, the ListView supports inserting new records, functionality provided by neither the GridView nor the Repeater. In fact, due to the extreme flexibility of the ListView, you may find fewer situations in which building a master/detail interface using the DetailsView is needed.

The Solution

The example presented here doesn't show off any of the native data-manipulation prowess of the ListView. Instead, it only displays and allows user selection of individual records, and passes all of the insertion, editing, and deleting functionality to an accompanying DetailsView.
Again, the tricky part is that with a ListView, you need to build your own presentation code. In the example, I'm displaying the records in a table; however, you could display the records however you want: as a bulleted list, a multicolumn grid, or totally free-form; whatever you want. You also need to provide buttons in the template to initiate the functionality you need. Here, in the ItemTemplate of the ListView, you'll see a button with CommandName="Select". That allows the datasource for the DetailsView to pick up the value of the record's primary key and fetch the individual record. Notice that in the SelectedItemTemplate, no button is defined. That means when a record is marked as selected in the ListView, the Select button won't appear.
The example presented here uses selected fields from the Employees table of the Northwind database, and also uses SqlDataSource for simplicity. If you have the Northwind database, you should be able to paste this code into a blank .aspx file and run it locally. Just be sure to change the connection strings in each SqlDataSource to point to your own Northwind database.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
 
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<div>         
<asp:ListView ID="lvwEmployees" runat="server" DataKeyNames="EmployeeID" DataSourceID="SqlDataSourceEmpList">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' />
td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
td>
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
td>
<td>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
td>
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select" />
td>
tr>
ItemTemplate>
<SelectedItemTemplate>
<tr style="background-color: yellow; font-weight: bold;">
<td>
<asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' />
td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
td>
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
td>
<td>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
td>
tr>
SelectedItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="1" style="border-collapse: collapse;
border-width: 1px;">
<tr runat="server" style="background-color: #DCDCDC; color: #000000;">
<th runat="server">
EmployeeID
th>
<th runat="server">
LastName
th>
<th runat="server">
FirstName
th>
<th runat="server">
Title
th>
tr>
<tr id="itemPlaceholder" runat="server">
tr>
table>
td>
tr>
table>
LayoutTemplate>
asp:ListView>         
<asp:SqlDataSource ID="SqlDataSourceEmpList" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees] ORDER BY [EmployeeID]">
asp:SqlDataSource>
<br />
<asp:DetailsView ID="dvwEmployee" runat="server" DataSourceID="SqlDataSourceEmp"
AutoGenerateRows="False" DataKeyNames="EmployeeID">
<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:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True"
NewText="Add" ButtonType="Button" />
Fields>
asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSourceEmp" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
DeleteCommand="DELETE FROM [Employees] WHERE [EmployeeID] = @EmployeeID" InsertCommand="INSERT INTO [Employees] ([LastName], [FirstName], [Title]) VALUES (@LastName, @FirstName, @Title)"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees] WHERE ([EmployeeID] = @EmployeeID)"
UpdateCommand="UPDATE [Employees] SET [LastName] = @LastName, [FirstName] = @FirstName, [Title] = @Title WHERE [EmployeeID] = @EmployeeID">
<SelectParameters>
<asp:ControlParameter ControlID="lvwEmployees" Name="EmployeeID" PropertyName="SelectedValue"
Type="Int32" />
SelectParameters>
<DeleteParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="EmployeeID" Type="Int32" />
UpdateParameters>
<InsertParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Title" Type="String" />
InsertParameters>
asp:SqlDataSource>         
div>
form>
body>
html>
Below is an example of the output you can expect:
listview-detailsview
Hey, I didn't say it was gonna be fancy. ;) That part is up to you!