Wednesday, December 19, 2007

HTML tutorial - Image maps

HTML tutorial - Image maps



alt="Beech hut" title="Beech hut - where you get changed">

alt="Life ring" title="Life ring - to help you swim">
alt="Flag" title="Flag - says if it safe to swim">






www.svdeals.com

Monday, November 26, 2007

Page 2 - Configuring a Linked Microsoft Access Server on SQL 2005 Server

Page 2 - Configuring a Linked Microsoft Access Server on SQL 2005 Server: "Configuring a Linked Microsoft Access Server on SQL 2005 Server - Linked Servers on SQL 2005 Server "



exec sp_addlinkedserver @server='AccessDb',
@srvproduct='Access',
@provider='Microsoft.Jet.OLEDB.4.0',
@datasrc='C:\data\Categories.mdb'

www.svdeals.com super value deals

Saturday, November 24, 2007

Using Queries to Convert Text Fields to Numerics

Using Queries to Convert Text Fields to Numerics: "Using Queries to Convert Text Fields to Numerics"


CDbl("3.2") =3.2

CDbl([MyField]) -->>>If MyField contains "3.2", 3.2If MyField contains "ABCD", a Type Mismatch error occurs

Friday, September 7, 2007

Thursday, September 6, 2007

Auto save download Archive website, Save web pages programmatically as .HTML asp.net

Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SavePage("http://localhost/tstProj/scrapage.aspx", "c:\scrapage.html")
End Sub
Private Sub SavePage(ByVal Url As String, ByVal FilePath As String)
Dim iMessage As CDO.Message = New CDO.Message
iMessage.CreateMHTMLBody(Url, _
CDO.CdoMHTMLFlags.cdoSuppressNone, "", "")
Dim adodbstream As ADODB.Stream = New ADODB.Stream
adodbstream.Type = ADODB.StreamTypeEnum.adTypeText
adodbstream.Charset = "US-ASCII"
adodbstream.Open()
iMessage.DataSource.SaveToObject(adodbstream, "_Stream")
adodbstream.SaveToFile(FilePath, _
ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
End Sub
End Class


For the above to compile you will need to add a reference to CDO, which is usually found sneaking deep in your C:\WINNT\System32 as C:\WINNT\System32\cdosys.dll


www.visli.com hot cake deals

Monday, August 20, 2007

NFL Picks for office 2007 asp.net C#

http://nfl.aspnet.googlepages.com/nflasp.net2.0code

Thursday, August 9, 2007

Excel Transpose Data

Excel Transpose Data


Excel: Transpose Data
If you have data in columns and you wish that data were in rows (or if you have data in rows that you wish were in columns), you do not need to retype it.
Simply select the data and hit the Copy button.
Next, select the cell that you want to become the upper left corner of the new range of data.
Go to the menu bar and choose Edit Paste Special. In the Paste Special dialog box, choose Transpose.

or
=TRANSPOSE(A1:A3)


www.svdeals.com super value deals

Thursday, August 2, 2007

Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'xxxxxxx\ASPNET' in C#, VB.NET, ASP.NET

Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'SANTOSH_LAPTOP\ASPNET' in C#, VB.NET, ASP.NET: "Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'xxxxxx\ASPNET'"



Open SQL Enterprise Manager
Locate Server
Open Security Folder => Logins
Now right-click and select “New Login…”
1) Create user with Name : ASPNET
2) Select Domain : “ServerName” to connect
3) Grant permissions to access database with “Server Roles” tab
4) Also permit database access with “Database Access” tab.



www.svdeals.com access database deals

Thursday, July 26, 2007

GridView Update All Rows At Once









' />




' />




' runat="server" Text='<%# Eval("coprowno") %>' />
' runat="server" Text='<%# Eval("coprowno") %>' />




' runat="server" Text='<%# Eval("cocomtot") %>' />
' runat="server" Text='<%# Eval("cocomtot") %>' />













using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Text;

public partial class Default6 : System.Web.UI.Page
{
private bool isEditMode = false;
protected bool IsInEditMode
{
get { return this.isEditMode; }
set { this.isEditMode = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
{
isEditMode = true;
BindData();
}
}
private void BindData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
string strSQL;
strSQL = "SELECT * FROM [ovowproty]";
//Response.Write(strSQL);
//Response.End();
SqlDataAdapter ad = new SqlDataAdapter(strSQL, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
MyGridView.DataSource = ds;
//isEditMode = true;
MyGridView.DataBind();


}
private void Update()
{
StringBuilder sb = new StringBuilder();
// build the query
foreach (GridViewRow row in MyGridView.Rows)
{
sb.Append("UPDATE ovowproty SET coprowno = '");
sb.Append((row.FindControl("coprowno") as TextBox).Text);
sb.Append("', ");
sb.Append("cocomtot = '");
sb.Append((row.FindControl("cocomtot") as TextBox).Text);
sb.Append("'");
sb.Append(" WHERE coOwnerID = ");
sb.Append(Convert.ToInt32((row.FindControl("coOwnerID") as Label).Text));
sb.Append(" and coProComTy=");
sb.Append("'");
sb.Append(Convert.ToString((row.FindControl("coProComTy") as Label).Text));
sb.Append("'");
}
// string connectionString = "Server=HCUBE008;Database=School;Trusted_Connection=true";
Response.Write(sb.ToString());
// Response.End();
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand myCommand = new SqlCommand(sb.ToString(), myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}




private string ConnectionString
{
get
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
return connectionString;
}
}






protected void Button2_Click(object sender, EventArgs e)
{
Update();
}
}



http://www.svdeals.com/ super value deals





Tuesday, July 24, 2007

Unable to Close Popup window using ASP.Net - .NET C#

Unable to Close Popup window using ASP.Net - .NET C#: "Unable to Close Popup window using ASP.Net "
Response.Write("");


Response.End();



http://www.svdeals.com/ super hit deals.

Monday, July 23, 2007

Tuesday, July 17, 2007

See Who Is Blocking Your SQL Server

See Who Is Blocking Your SQL Server: "See Who Is Blocking Your SQL Server"
See Who Is Blocking Your SQL Server
If you have ever monitored any blocking problems in SQL Server, you know that sp_who only shows you the spid (SQL Server's internal Process ID) that is causing the blocking for each spid that is blocked. Often a blocked spid is shown as causing blocking for another spid. To see the spid (or spids) that started the whole mess off, execute the following SQL:
SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, convert(char(12), l.name) login_name
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM master..sysprocesses p
JOIN master..sysdatabases d ON p.dbid = d.dbid
JOIN master..syslogins l ON p.suid = l.suid
WHERE p.blocked = 0
AND EXISTS ( SELECT 1
FROM master..sysprocesses p2
WHERE p2.blocked = p.spid )
We built this into our own version of sp_who, called sp_hywho. See the listing below.
Code for sp_hywho: if exists (select * from sysobjects
where id = object_id('dbo.sp_hywho')
and sysstat & 0xf = 4)
drop procedure dbo.sp_hywho
GO
Create Procedure sp_hywho
( @vcDBName sysname = NULL )
AS
SET NOCOUNT ON
IF EXISTS ( SELECT 1
FROM master..sysprocesses p
WHERE p.blocked = 0
AND EXISTS ( SELECT 1
FROM master..sysprocesses p2
WHERE p2.blocked = p.spid ) )
BEGIN
PRINT "Blocking caused by:"
PRINT ""
SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, convert(char(12), l.name) login_name
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM master..sysprocesses p
JOIN master..sysdatabases d ON p.dbid = d.dbid
JOIN master..syslogins l ON p.suid = l.suid
WHERE p.blocked = 0
AND EXISTS ( SELECT 1
FROM master..sysprocesses p2
WHERE p2.blocked = p.spid )
AND (p.dbid = DB_ID( @vcDBName ) OR @vcDBName IS NULL)
ORDER BY 2,IsNull(Ltrim(program_name),"ZZZZZZZZZ"),4,5
PRINT ""
END
SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, convert(char(12), l.name) login_name
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM master..sysprocesses p
JOIN master..sysdatabases d ON p.dbid = d.dbid
JOIN master..syslogins l ON p.suid = l.suid
WHERE (p.dbid = DB_ID( @vcDBName ) OR @vcDBName IS NULL)
ORDER BY 2,IsNull(Ltrim(program_name),"ZZZZZZZZZ"),4,5
SET NOCOUNT OFF
GO
if exists (select * from sysobjects
where id = object_id('dbo.sp_hywho')
and sysstat & 0xf = 4)
GRANT EXEC ON dbo.sp_hywho TO PUBLIC
GO

www.svdeals.com super hotttt dealssss

Friday, July 13, 2007

Monday, July 9, 2007

Web Server Calendar Control in ASP.NET 2.0

Web Server Calendar Control in ASP.NET 2.0: "Web Server Calendar Control in ASP.NET 2.0"

www.svdeals.com

Control ctl00 of type 'GridView' must be placed inside a form tag with runat=server

CodeSnip: Exporting GridView to Excel: ASP Alliance

This is pretty confusing, since your GridView is already inside the form tags and also contains the runat = server attribute. You can easily resolve this error by adding the following lines.

Listing 3: Overiding VerifyRenderingInServerForm Method
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}


www.svdeals.com super hot deals

Thursday, July 5, 2007

How to convert string to double C# Friends

How to convert string to double C# Friends: "How to convert string to double"

www.svdeals.com

gridView cummulative total on level break

if (e.Row.Cells[1].Text!=shiptp122)
{
RunTot = 0;
}
RunTot += (Convert.ToInt32(e.Row.Cells[2].Text));
e.Row.Cells[3].Text = Convert.ToString(RunTot);
shiptp122 = e.Row.Cells[1].Text;

www.svdeals.com cummulative total

Tutorial 15: Displaying Summary Information in the GridView's Footer

Tutorial 15: Displaying Summary Information in the GridView's Footer: "Tutorial 15: Displaying Summary Information in the GridView's Footer"

cummulative sum

deals - www.visli.com

GridViewRowCollection.Count Property (System.Web.UI.WebControls)

GridViewRowCollection.Count Property (System.Web.UI.WebControls): "GridViewRowCollection.Count Property"


http://www.visli.com/ super duper deals

Tuesday, July 3, 2007

Creating a Crosstab Report in Visual Studio 2005 Using Crystal Reports: ASP Alliance

Creating a Crosstab Report in Visual Studio 2005 Using Crystal Reports: ASP Alliance: "Creating a Crosstab Report in Visual Studio 2005 Using Crystal Reports"

www.svdeals.com

CodeSnip: How to Display Sum Total in the Footer of the GridView Control: ASP Alliance

CodeSnip: How to Display Sum Total in the Footer of the GridView Control: ASP Alliance: "CodeSnip: How to Display Sum Total in the Footer of the GridView Control"


www.svdeals.com

MS SQL Server: Rollup with Datetime by Year

MS SQL Server: Rollup with Datetime by Year: "Title:
Rollup with Datetime by Year"
SELECT CASE WHEN (Grouping (DATEPART(year,date_and_time)) = 1) THEN '- All Years -' ELSE CAST(DATEPART(year,CAST(SUM(CAST(DATEPART(year,date_and_time) as int))/count(*) as datetime))as varchar) END as 'Year',CAST(sum(attempt) as varchar) as 'Attempts', CAST(sum(success) as varchar) as 'Success', CAST(avg((success/attempt)*100) as varchar)+'%' as 'Success Rate', CAST(sum(failure) as varchar) as 'Failure', CAST(avg((failure/attempt)*100) as varchar)+'%' as 'Failure Rate', CAST(sum(cancelled) as varchar) as 'Cancelled', CAST(avg((cancelled/attempt)*100) as varchar)+'%' as 'Cancelled Rate', CAST(sum(macro_no_value) as varchar) as 'Macro', CAST(avg((macro_no_value/attempt)*100) as varchar)+'%' as 'Macro Rate' FROM apr_stats GROUP BY (DATEPART(year,date_and_time)) with ROLLUP ORDER BY (DATEPART(year,date_and_time))


www.svdeals.com super value deals

Thursday, June 28, 2007

How to: Set GridView Web Server Control Column Width Dynamically

How to: Set GridView Web Server Control Column Width Dynamically: "How to: Set GridView Web Server Control Column Width Dynamically "
How to: Set GridView Web Server Control Column Width Dynamically
By default, columns in the GridView control are sized automatically. Columns render as HTML table cells (td elements) without width information; most browsers size table cells to allow for the widest content in the column.
If it is required, you can set the width of individual columns in the GridView control programmatically. This is useful, if the width of the column depends on information that is available only at run time. For example, you might size a column according to its contents—that is, based on the data that the GridView control binds to.
The basic technique for setting column width involves setting the Width property of a column template. If you want the width to be set according to its contents, you can handle the RowDataBound event. This makes the data for a row available to you for examination.
To set column width dynamically
In code, set the Width property of the ItemStyle property for a GridView control column to the width that you want.
The following code example shows how to set the width of all the columns in the GridView1 control to the value that a user enters in a text box.
Visual Basic
Copy CodeProtected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Try
Dim colWidth As Integer
colWidth = CInt(Server.HtmlEncode(TextBox1.Text))
If colWidth > 0 Then
For i As Integer = 0 To GridView1.Columns.Count - 1
GridView1.Columns(i).ItemStyle.Width = colWidth
Next
End If
Catch
' Report error.
End Try
End Sub
C#
Copy Codeprotected void Button1_Click(object sender, EventArgs e)
{
try
{
int colWidth = Int16.Parse(Server.HtmlEncode(TextBox1.Text));
if (colWidth > 0)
{
for (int i = 0; i < GridView1.Columns.Count; i++)
{
GridView1.Columns[i].ItemStyle.Width = colWidth;
}
}
}
catch
{
// Report error.
}
}
To set column width based on data contents
Create a handler for the RowDataBound event.
The RowDataBound event is raised each time that a new row is data-bound in the grid and gives you access to the data for each row.
In the event handler, do the following:
Create a DataRowView object and assign to it the DataItem value for the current grid row.
The DataItem property is typed as an object. Therefore, you must cast it.
Test for a data row (DataControlRowType) to make sure that you are working with a data-bound row and not a header or footer.
From the DataRowView object, extract the data value that you want to examine.
Set the Width property for the ItemStyle property.
Set the Wrap property of the ItemStyle property to false.
If the Wrap property is false, the column is automatically resized.
The following code example shows how to set the width of a column (in this case, the third column) based on the width of the widest data element of the second column. The RowDataBound event handler is called one time for each data row that is displayed by the GridView control. The code stores the character count of the widest element in a protected page member. The code sets the width of the column to the character count times 30 (an arbitrary multiplier).
Visual Basic
Copy CodeProtected widestData As Integer
Protected Sub GridView1_RowDataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
Dim drv As System.Data.DataRowView
drv = CType(e.Row.DataItem, System.Data.DataRowView)
If e.Row.RowType = DataControlRowType.DataRow Then
If drv IsNot Nothing Then
Dim catName As String = drv(1).ToString()
Dim catNameLen As Integer = catName.Length
If catNameLen > widestData Then
widestData = catNameLen
GridView1.Columns(2).ItemStyle.Width = _
widestData * 30
GridView1.Columns(2).ItemStyle.Wrap = False
End If
End If
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
widestData = 0
End Sub
C#
Copy Codeprotected int widestData;
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
System.Data.DataRowView drv;
drv = (System.Data.DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (drv != null)
{
String catName = drv[1].ToString();
Response.Write(catName + "/");

int catNameLen = catName.Length;
if (catNameLen > widestData)
{
widestData = catNameLen;
GridView1.Columns[2].ItemStyle.Width =
widestData * 30;
GridView1.Columns[2].ItemStyle.Wrap = false;
}

}
}
}
protected void Page_Load(object sender, EventArgs e)
{
widestData = 0;
}
See Also
Other ResourcesGridView Web Server Control


www.svdeals.com super value deals

Wednesday, June 27, 2007

Running total sql-server group by

OrderID Oredrty OrderAmt OrderDate
1 SO 10 ########
2 SR 36 ########
3 SO 25 ########
4 SR 21 ########
5 SO 10 ########
6 CO 100 ########
7 CO 20 ########
8 SO 100 ########

SELECT a.OrderID, a.OrderAmt,A.Oredrty, SUM(b.OrderAmt)RunningTotal FROM orders a
CROSS JOIN orders b WHERE (b.OrderID <= a.OrderID AND b.Oredrty = a.Oredrty)
GROUP BY A.Oredrty,a.OrderID,a.OrderAmt
ORDER BY A.Oredrty,a.OrderID,a.OrderAmt

www.svdeals.com super value deals

Calculating Running Totals - SQLTeam.com

Calculating Running Totals - SQLTeam.com: "Calculating Running Totals"
Roger writes "Is there a way to retrive a field value from the previously read row in order to use it to calculate a field in the current row . . ." -->
For example: day sales cumu_total
1 120 120
2 60 180
3 125 305
4 40 345
In order to calculte the cumulative total I need to know the previous cumulative total (cumulative total could be any other calculation). I did this in MySQL by using variables to temporarily hold values between rows but SQL server doesn't assinging variables in retrieval statements. Is it possible to do this in a Select statement?"
The answer to the questions is "yes", you can solve this problem with a single SELECT statement. Instead of just showing the solution that came to mind, though, I want to take a look at three ways to solve the problem.
Creating the Test DataI used the code shown below to create the base table and a few thousand rows of test data. It is important to add enough data so that the efficiency of the three solutions can be accurately measured. In other words, with only a few rows of data they all seem efficient. CREATE TABLE Sales (DayCount smallint, Sales money)
CREATE CLUSTERED INDEX ndx_DayCount ON Sales(DayCount)
go
INSERT Sales VALUES (1,120)
INSERT Sales VALUES (2,60)
INSERT Sales VALUES (3,125)
INSERT Sales VALUES (4,40)
DECLARE @DayCount smallint, @Sales money
SET @DayCount = 5
SET @Sales = 10
WHILE @DayCount < 5000
BEGIN
INSERT Sales VALUES (@DayCount,@Sales)
SET @DayCount = @DayCount + 1
SET @Sales = @Sales + 15
END
The Three Solutions
The three different solutions I tested are shown below. The execution time with and without a clustered index on DayCount is shown at the top of each batch.
Solution 1: Temp Table/Cursor
(NoIndex = 2 secs, Index = 2 secs) CREATE TABLE #Sales (DayCount smallint, Sales money, RunningTotal money)
DECLARE @DayCount smallint,
@Sales money,
@RunningTotal money
SET @RunningTotal = 0
DECLARE rt_cursor CURSOR
FOR
SELECT DayCount, Sales
FROM Sales
OPEN rt_cursor
FETCH NEXT FROM rt_cursor INTO @DayCount,@Sales
WHILE @@FETCH_STATUS = 0
BEGIN
SET @RunningTotal = @RunningTotal + @Sales
INSERT #Sales VALUES (@DayCount,@Sales,@RunningTotal)
FETCH NEXT FROM rt_cursor INTO @DayCount,@Sales
END
CLOSE rt_cursor
DEALLOCATE rt_cursor
SELECT * FROM #Sales ORDER BY DayCount
DROP TABLE #Sales

Solution 2: The "Celko" Solution
(NoIndex = 25 secs, Index = 20 secs) SELECT DayCount,
Sales,
Sales+COALESCE((SELECT SUM(Sales)
FROM Sales b
WHERE b.DayCount < a.DayCount),0)
AS RunningTotal
FROM Sales a
ORDER BY DayCount

Solution 3: The "Guru's Guide" Solution
(NoIndex = 38 secs, Index = 17 secs) SELECT a.DayCount,
a.Sales,
SUM(b.Sales)
FROM Sales a
CROSS JOIN Sales b
WHERE (b.DayCount <= a.DayCount) AS RunningTotal
GROUP BY a.DayCount,a.Sales
ORDER BY a.DayCount,a.Sales
Solution 1 uses a temporary table and a cursor and executes extremely fast. I must admit that my original intent was to show this solution as the way *not* to solve the problem. In general, I tell developers to avoid cursors at all costs. In this particular case, however, the cursor approach is much quicker than the single SELECT solutions.
Solution 2 is the one that came to mind when I originally read the question. I attribute the solution to Joe Celko, because it can be found in his SQL for Smarties book and I'm sure I learned about it in one of his posts in the SQL Server newsgroups.
The tricky part about this solution is the use of a correlated subquery and the COALESCE function. A correlated subquery is one that executes for each row in the outer query. The inner query sums the Sales for rows with a DayCount value less than the current row.
The COALESCE function returns the first non-NULL value in its list of values. The first row processed returns a NULL for SUM(Sales) because there is no DayCount less than it's value. When this happens a 0 is returned and added to the Sales value.
Solution 3 is labeled the "Guru's Guide" because it can be found in Ken Henderson's enormously popular "The Guru's Guide to Transact-SQL." I would have never come up with this solution, but I guess that's what makes Ken the Guru and me a Guru wannabee.
This solution uses a CROSS JOIN and table aliases to join the Sales table with itself. This causes each row in the left table (Sales a) to be joined with each row in the right table (Sales b) where the DayCount in b in less than the DayCount in a. The SUM(b.Sales) and the GROUP BY a.DayCount, a.Sales then allow the running total for each row to be calculated. If you are having trouble figuring out how this works draw a layout of two instances of Sales side-by-side, and then draw lines from a row in the left table to the rows in the right table that meet the WHERE condition.
When I first ran the tests I did not have a clustered index on DayCount. Upon realizing DayCount is a prime candidate for a clustered index, I added it and re-ran the tests. The execution time for Solution 3 was significantly reduced after the index was created because of the number of rows joined by the CROSS JOIN.
And as an FYI, the server I used to tests these solutions is a Compaq ML370 with dual 600's and 1 GB RAM--your results may vary.


www.svdeals.com super deals

Tuesday, June 26, 2007

Format Grid Columns at Run Time

Format Grid Columns at Run Time: "Format Grid Columns at Run TimeFormat Grid Columns at Run Time"

Gridview Conditional Formatting ?

Gridview Conditional Formatting ?: "ASP Net - Gridview Conditional Formatting ?"


http://www.svdeals.com/ deals fo the day

Monday, June 25, 2007

Crystal Report for Visual Studio .NET: ASP Alliance

Crystal Report for Visual Studio .NET: ASP Alliance

An overview of Crystal Reports. Walkthroughs show how to use both Pull and Push methods as well as exporting the report file into other formats.

by Eric LandesFeedback
Average Rating: Views (Total / Last 10 Days): 349114/ 2925
Article Contents:
Overview
Introduction
Getting a Feel of It - Using an Existing Crystal Report File in Your .aspx Page
Crystal Reports Walkthrough - Using the Pull Model
Crystal Reports Walkthrough - Using the Push Model
Exporting the Report File into Other Formats
Overview
[ Back To Top ]
Editor's Note: The first edition of this article was written by Ajay Varghese.
Before we started off this small research on Crystal Reports for Visual Studio .NET, my friend and I were inquisitive about the complexity with regard to its implementation into our web application. A week later, with a lot of effort going into hunting for the ‘how-to’ documentation online, we have managed to integrate some simple reports into our ASP.NET application and try some neat tricks with it!!
This article is a compilation of required material to kick-start the process of implementing Crystal Reports into your .NET web application and should reduce your frustrating efforts (spent for the same research that we made) to a trifle by using these step-by-step walkthroughs. To get the best out of this article, the reader should have a basic Knowledge of database connections in ASP.NET and use Visual Studio .NET for the development. Please note that we have tested the below given sample code illustrations with the beta 2 version of Visual Studio .NET only.
The topics that we have covered here are :
1) Introduction
2) Getting a feel of it - Using an existing Crystal Report file in your .aspx page
3) Crystal Reports Walkthrough - using the Pull Model
4) Crystal Reports Walkthrough - using the Push Model
5) Exporting the Report file into other formats
Introduction
[ Back To Top ]
Crystal Report comes in various flavors and the one that is required for building reports for .NET is "Crystal Report for Visual Studio .NET". It exposes a rich programming model with which we could manipulate its properties and methods during runtime. If you are developing your .NET applications using Visual Studio .NET then you won’t have to install any additional software as it is already built into Visual Studio .NET.
---- Advantages -----
Some of the major advantages of using Crystal Report for Visual Studio .NET are :
- Rapid report development
- Can extend it to complicated reports with interactive charts
- Exposes a report object model using which it can interact with other controls on the web form
- Can programmatically export the reports into widely used formats like .pdf, .doc, .xls, .html and .rtf

---- The Architecture ----
The various components that make up a simple implementation of Crystal Report as a 2-tier architecture, required for web applications are
The Client :
The client only needs a browser to access the reports which are embedded into the .aspx pages.
The Web Server hosts the :
- Crystal Report Engine (CREngine.dll)
Along with other tasks like merging the data with the report file, exporting reports into different formats, etc., it is the Report Engine that converts your Crystal Report into plain HTML that is passed on to your .aspx page.
- Crystal Report Designer (CRDesigner.dll)
The reports are created from scratch using the Crystal Report Designer, with which you could design the titles, insert data, formulas, charts, sub-reports, etc.
- The .rpt Report file
The first step to implement a report into your web application would be to create it using the Crystal Report Designer interface. You will find some ready-made .rpt samples provided with the default installation.
- The Data Source
The way your .rpt file gets the data depends on which method you choose. You can choose to make Crystal Report itself to fetch your data without writing any code for it or you can choose to manually populate a dataset and pass it on to the report file. We will look at the various possibilities a little later in this article.
- Crystal Report Viewer web form Control (CRWebFormViewer.dll)
The Crystal Report Viewer control is a web form control that can be inserted into your .aspx page. It can be thought of as a container that hosts the report on the .aspx page.
Note : In a more complex implementation, the reporting server and the web server could be on different physical servers, where the web server would make an HTTP request to the reporting server. The Crystal Reports could also be implemented as a web service.
---- Implementation Models -----
Fetching the data for the Crystal Report could be done by using any of the following methods :
- Pull Model :
where in Crystal Report handles the connection to the database using the specified driver and populates the report with the data, when requested.
- Push Model :
where it is the developer who has to write code to handle the connection and populate the dataset, and pass it on to the report. The performance can be optimized in this manner by using connection sharing and manually limiting the number of records that are passed on to the report.
---- Report Types ----
Crystal Report Designer can load reports that are included into the project as well as those that are independent of the project.
- Strongly-typed Report :
When you add a report file into the project, it becomes a ‘strongly-typed’ report. In this case, you will have the advantage of directly creating an instance of the report object, which could reduce a few lines of code, and caching it to improve performance. The related .vb file, which is hidden, can be viewed using the editor’s ‘show all files’ icon in the Solution Explorer.
- Un-Typed Report :
Those reports that are not included into the project are ‘un-typed’ reports. In this case, you will have to create an instance of the Crystal Report Engine’s 'ReportDocument' object and manually load the report into it.
---- Other things you should know ----
- Though the Crystal Report Viewer control comes with some cool in-built options like zooming, page navigation, etc., it does not have a custom print option. You will have to depend on the browser’s print feature.
- An un-registered copy of Crystal Report for Visual Studio .NET will remain active only for the first 30 uses, after which the ‘save’ option will be disabled. To avoid this, all you have to do is register the product with http://www.crystaldecisions.com/ for which you are not charged.
- The default installation will service only 5 concurrent users. To support more users, you will have to buy additional licenses from http://www.crystaldecisions.com/
Getting a Feel of It - Using an Existing Crystal Report File in Your .aspx Page
[ Back To Top ]
Lets take a look at how we could get this done the fast way to get a feel of how a Crystal Report file would look like in your web form.
1) Drag and drop the "Crystal Report Viewer" from the web forms tool box on to the .aspx page

2) Bring up the properties window for the Crystal Report Viewer control
3) Click on the [...] next to the "Data Binding" Property and bring up the data binding pop-up window
4) Select "Report Source" from the "Bindable properties" section on the left side

5) Select the "Custom Binding Expression" radio button, on the right side bottom of the window and specify the sample .rpt filename and path as
"C:\Program Files\Microsoft Visual Studio.NET\Crystal Reports\Samples\Reports\General Business\World Sales Report.rpt"(including the double quotes) and Click "ok"

Note : The ‘World Sales Report.rpt’ file is created as a part of Visual Studio .NET installation. If you have specified a different directory during installation then make necessary changes to the above specified path.
In a couple of seconds you should see the Report Viewer Control load a preview of the actual report during design time itself. The reason for the data being loaded during design time is that the report has been saved with the data.
The above steps actually insert the following code into your .aspx page :

above the Page Directive and
' Height="50px" Width="350px" runat="server">

within the
section of the page.
6) Call the DataBind method, on the Page Load Event of the Code Behind file (.aspx.vb).
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
DataBind()
End Sub

7) Save, build and run your page.
There !!! You have a web form page with a Crystal Report file embedded into it.
Crystal Reports Walkthrough - Using the Pull Model
[ Back To Top ]
We would be using the following steps to implement Crystal Reports using the Pull Model :
1. Create the .rpt file (from scratch) and set the necessary database connections using the Crystal Report Designer interface.
2. Place a CrystalReportViewer control on the .aspx page and set its properties to point to the .rpt file that we created in the previous step.
3. Call the databind method from your code behind page.
Creating the .rpt File:
1) Add a new Crystal Report to the web form by right clicking on the "Solution Explorer", selecting "Add" --> "Add New Item" --> "Crystal Report".

2) On the "Crystal Report Gallery" pop up, select the "As a Blank Report" radio button and click "ok".


3)This should open up the Report File in the Crystal Report Designer


4) Right click on the "Details Section" of the report, and select "Database" -> "Add/Remove Database"

5) In the "Database Expert" pop up window, expand the "OLE DB (ADO)" option which should bring up another "OLE DB (ADO)" pop up

6) In the "OLE DB (ADO)" pop up, Select "Microsoft OLE DB Provider for SQL Server" and click "Next"


7) Specify the connection information
Server : HomePC (Make use of your server name here)
User Id : sa
Password :
Database : Pubs

8) Click "Next" and then click "Finish"

9) Now you should be able to see the Database Expert showing the table that have been selected

10) Expand the "Pubs" database, expand the "Tables", select the "Stores" table and click on ">" to include it into the "Selected Tables" section.


11) Now the Field Explorer should show you the selected table and its fields under the "Database Fields" section, in the left window.

12) Drag and drop the required fields into the "Details" section of the report. The field names would automatically appear in the "Page


www.svdeals.com

Walkthrough: Creating a Nested GridView Control

Walkthrough: Creating a Nested GridView Control: "Walkthrough: Creating a Nested GridView Control "

Tuesday, June 12, 2007

AJAX DropDownList - The Code Project - ASP.NET

AJAX DropDownList - The Code Project - ASP.NET: "AJAX DropDownList"

ASP.NET AJAX > Sample ASP.NET AJAX Application

ASP.NET AJAX > Sample ASP.NET AJAX Application: "Adding an UpdatePanel Control to an ASP.NET Web Page"

In Solution Explorer, right-click the name of the site and then click Add New Item.
The Add New Item dialog box is displayed.
Under Visual Studio installed templates, select Web Form.
Name the new page Employees.aspx and clear the Place code in separate file check box.
Select the language you want to use.
Click Add.
Switch to Design view.
In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to the page.

Drag an UpdatePanel control from the toolbox and drop it underneath the ScriptManager control.



www.svdeals.com super value deals

Thursday, May 24, 2007

OFBiz Eclipse - Debugging OFBiz

OFBiz Eclipse - Debugging OFBiz: "OFBiz Eclipse - Debugging OFBiz"
Preliminary Setup
If you have not already done so, import ofbiz into Eclipse with File > Import > "Existing Projects into Workspace". Note that the name of the project and its name in .project file must be the same.
The next step is to enable Eclipse to work on your .xml, .ftl, and .bsh files. First, install an XML editor such as the free XMLBuddy. Then, install the Freemarker Eclipse plug-in. Finally, go to Windows > Preferences > General > Editors > File Associations and add "*.bsh" and associate it with the Scrapbook editor.
You should also set your editors to be compatible with OFBiz coding convention. For Java files, go to Windows > Preferences > Java > Code Style > Formatter and create a new profile. Set your tabs to 4 spaces. Similarly, go to Windows > Preferences > XMLBuddy > Formatting and click on "Use spaces for tabs", or configure your XMLZ editor likewise.
You can toggle between code view and directory/file view by switching Eclipse from "Java Perspective" our "Java Browsing" and "Resources". If you have new components, add them to your .classpath file as a so they can be viewed in the Java views.
Java Debugging with Eclipse
Click on the green bug icon on the Eclipse toolbar, or click on "Run" on the top menu bar, then "Debug". Then click on "Java Application", click on "New" to create a new configuration for OFBIZ.



www.svdeals.com super value hot deals

Tuesday, May 22, 2007

I have difficulty in starting Eclipse

I have difficulty in starting Eclipse: "Java - I have difficulty in starting Eclipse"

Don't rely on env vars. Start eclipse with option-vm "C:\Program Files\Java\jre1.5.0_06\bin\java"



www.svdeals.com super value deals

Getting started with the Eclipse Platform

Getting started with the Eclipse Platform: "What is Eclipse?What is Eclipse?What is Eclipse?"


www.svdeals.com super value hot deals

Tuesday, May 15, 2007

Nabble - Query-based insertion or updating of BLOB values is not supported. -- ????

Nabble - Query-based insertion or updating of BLOB values is not supported. -- ????: "Query-based insertion or updating of BLOB values is not supported"


www.svdeals.com super value deals

MySQL OLE DB Provider

MySQL OLE DB Provider: "MySQL OLE DB Provider"


www.svdeals.com super value deals

MySQL OLEDB Provider Using MySQL Provider with SQL Server DTS Wizard

MySQL OLEDB Provider: "Using MySQL Provider with SQL Server DTS Wizard"


www.svdeals.com super value deals

How do I import delimited data into MySQL?

How do I import delimited data into MySQL?

LOAD DATA LOCAL INFILE '/importfile.csv' INTO TABLE test_table FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1, filed2, field3);



www.svdeals.com super value deals

Monday, May 14, 2007

Eclipse BIRT Home

Eclipse BIRT Home: "Business Intelligence and Reporting Tools"
BIRT is an open source Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports.



www.svdeals.com super value deals

SQL INSERT INTO Statement

SQL INSERT INTO Statement: "INSERT INTO Store_Information (store_name, Sales, Date)
SELECT store_name, Sales, Date
FROM Sales_Information
WHERE Year(Date) = 1998"



www.svdeals.com super value deals

Wednesday, May 9, 2007

Tuesday, May 8, 2007

ASP.NET 2.0: Using the Menu Control

ASP.NET 2.0: Using the Menu Control: "ASP.NET 2.0 : Using the Menu Control "
Here we will take a look at two different ways to set up the Menu Control. One, with the default SiteMap provider using a standard Xml web.siteMap file, and the other using a SqlSiteMapProvider, an example of which was recently published by Jeff Prosise in his "Wicked Code" column in MSDN magazine.
To start off, lets create a new MasterPage to hold our menus, which provides us with a ContentPlaceHolder control that all pages deriving from our MasterPage place their content into. First the HTML code, then some notes:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Default.master.cs" Inherits="_Default" %>








Orientation="Horizontal" CssClass="toolbar" Width="96px">





















What I have above is a Master Page declaration, an inline CSS stylesheet we will use for our menus, two asp:Menu tags and two asp:SiteMapDataSource tags. You can get all of this by simple right-clicking your Web Site in Solution Explorer, and choosing Add New Item, then MasterPage from the Installed Templates window. You can get the menu and SiteMapDataSource controls by simply dragging them onto your new Master Page from the Toolbox.
Each Menu Control needs a SiteMapDataSource. If none is specified, the default XmlSiteMapProvider is used, and it requires a "web.siteMap" xml file which you can create by choosing Add New Item and "sitemap". The web.siteMap file structure is a nested Nodelist that looks like this:
description="Home"
url="SiteMaps.aspx?id=1">
url="SiteMaps.aspx?id=2">



description="The Research Site"
url="SiteMaps.aspx?id=7">
url="SiteMaps.aspx?id=8"/>
url="SiteMaps.aspx?id=9"/>
url="SiteMaps.aspx?id=10" />



You can see that we have a "Home" siteMapNode, and that we can nest additional siteMapNodes to get the familiar tree-like dropdown menu effect. Each node has a title, description, and url. There are other members and properties, you can get the whole story at the documentation.
Since we have more than one SiteMapDataSource, we define the providers in our web.config file like so:



providerName="System.Data.SqlClient" />




securityTrimmingEnabled="false"
connectionStringName="SiteMapConnectionString" />



Note above that we have a connection string defined specifically for our SqlSiteMapProvider, and that it is specifically referenced in the defaultProvider siteMap element. I've also added back in the XmlSiteMapProvider since it is no longer the default, and have provided the required siteMapFile="web.SiteMap" attribute for it.
In my SiteMap database table, I've defined my nodes in the familar parent - child self-referencing table format:
You can see that the Provider will simply read this out into a SqlDataReader, and create the SiteMapNodes. You can look at Prosise's code for the SqlSiteMapProvider included, and see that it is very easy to create one. This datasource is assigned to one of my menus with the DataSourceID attribute of the asp:Menu tag declaration. The rest is just choosing some of the long list of properties that can be set via the Property Sheet for the control. In this case, I've decided to add a cool 3-D like gradient by simply setting the CSSClass attribute to my "toolbar" CSS class defined in the inline stylesheet. The result, when any of the pages comes up, looks like this:
I didn't spend as much time on this as I normally would, so a lot of the kind of fine-tuning one would expect for a production app is not present. However, the downloadable zip file below includes everything you need to get started, including a SQL Script that will create the "TEST" database and SiteMap table, and populate it with what you see above. Just unzip it to the folder of your choice, run the Sql Script, and in Visual Studio.NET 2005, choose File / Open / Web Site / FileSystem and point it to your folder. The "Cassini-Meanie" built in web server will take it from there. Note that I do not have Roles Authorization enabled for this particular example, but it is extremely easy to "turn on" and integrates beautifully with Forms Authentication and similar authentication schemes.
Have fun!


www.svdeals.com super value deals

Forms control in HTML documents

Forms in HTML documents: "Control types"



www.svdeals.com super value deals

Dynamically Generating PDFs in .NET - Developer Fusion: Connecting Developers Worldwide. C#, .NET, VB, Java, PHP and XML tutorials & source code

Dynamically Generating PDFs in .NET - Developer Fusion: Connecting Developers Worldwide. C#, .NET, VB, Java, PHP and XML tutorials & source code: "Dynamically Generating PDFs in .NET "



www.svdeals.com super value deals

Monday, May 7, 2007

GridView CheckBox Selection With a Twist - The Code Project - C# Controls

GridView CheckBox Selection With a Twist - The Code Project - C# Controls: "GridView CheckBox Selection With a Twist"


www.svdeals.com super value deals

GridView.PageIndexChanged Event (System.Web.UI.WebControls)

GridView.PageIndexChanged Event (System.Web.UI.WebControls): "GridView.PageIndexChanged Event "


www.svdeals.com super value deals

GridViewGuy

GridViewGuy: "GridView Custom Paging "
Introduction:
GridView control provides you with an easy way to display the number of items on the page without taking much space with the help of paging. You can enable the paging feature in the GridView control within seconds. The built in paging is pretty good if you are fetching less than 100 items as soon as the number of items increases the performance suffers. The main reason for the performance kill is that whenever you go to a new page of the GridView it fetches all the items from the database. In this article I will demonstrate how you can use custom paging to improve the performance of the GridView paging.
Database and Stored Procedure:
I will be using the good old Northwind database. The stored procedure is written by Greg Hamilton. You can view Greg Hamilton's article A More Efficient Method for Paging Through Large Result Sets on www.4guysfromrolla.com. Greg created a very efficient stored procedure that works without the use of temporary table or the TABLE variable.
I have modified the stored procedure by adding few fields. Here is the modified version of the stored procedure:
CREATE PROCEDURE [usp_GetProducts]
@startRowIndex int,@maximumRows int, @totalRows int OUTPUT
AS
DECLARE @first_id int, @startRow int
SET @startRowIndex = (@startRowIndex - 1) * @maximumRows
IF @startRowIndex = 0 SET @startRowIndex = 1
SET ROWCOUNT @startRowIndex
SELECT @first_id = ProductID FROM Products ORDER BY ProductID
PRINT @first_id
SET ROWCOUNT @maximumRows
SELECT ProductID, ProductName FROM Products WHERE ProductID >= @first_id ORDER BY ProductID SET ROWCOUNT 0
-- GEt the total rows
SELECT @totalRows = COUNT(ProductID) FROM ProductsGO
I highly recommend that you check out Greg’s article in which he explained in detail how the stored procedure works.
Displaying Paged Data on the Page:
I will be paging through the records using the “Next” and the “Previous” buttons. The Label control will display our current location in the paged GridView. Let’s first set up some of the variables.
protected int currentPageNumber = 1; private const int PAGE_SIZE = 10;
The currentPageNumber represents the current page of the GridView and the PAGE_SIZE is the total number of records displayed on each page. You can also allow the user to adjust the page size using a DropDownList but that is not covered in this article.
Next, we need to bind the data source to the GridView. Let’s check out the BindData method as a whole and later I will dissect it so you will have a better idea.
private void BindData() { string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true"; SqlConnection myConnection = new SqlConnection(connectionString); SqlCommand myCommand = new SqlCommand("usp_GetProducts", myConnection); myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("@startRowIndex", currentPageNumber); myCommand.Parameters.AddWithValue("@maximumRows", PAGE_SIZE); myCommand.Parameters.Add("@totalRows", SqlDbType.Int, 4); myCommand.Parameters["@totalRows"].Direction = ParameterDirection.Output;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet(); ad.Fill(ds);
gvProducts.DataSource = ds; gvProducts.DataBind();
// get the total rows double totalRows = (int)myCommand.Parameters["@totalRows"].Value;
lblTotalPages.Text = CalculateTotalPages(totalRows).ToString();
lblCurrentPage.Text = currentPageNumber.ToString();
if (currentPageNumber == 1) { Btn_Previous.Enabled = false;
if (Int32.Parse(lblTotalPages.Text) > 0) { Btn_Next.Enabled = true; } else Btn_Next.Enabled = false;
}
else { Btn_Previous.Enabled = true;
if (currentPageNumber == Int32.Parse(lblTotalPages.Text)) Btn_Next.Enabled = false; else Btn_Next.Enabled = true; } }
Now, let’s take a look at the above code in more detail. I am sending the currentPageNumber and the PAGE_SIZE into the database so I can get the data for the current page. The totalRows variable returns the total number of rows in the table. Once, I got the totalRows I calculated the total number of pages that will be used for this GridView. The total number of pages are calculated by using a small helper function.
private int CalculateTotalPages(double totalRows) { int totalPages = (int) Math.Ceiling(totalRows / PAGE_SIZE);
return totalPages; }
At the end of the BindData method there are some conditional checks which ensure that the next and previous buttons are only displayed when applicable.
Attaching the Events to the Buttons:
The final thing that is left is to attach the events to the Button controls. Check out the following code in which I created two button controls.

Both the buttons calls the ChangePage event which is shown below: // This method will handle the navigation/ paging index protected void ChangePage(object sender, CommandEventArgs e) { switch (e.CommandName) { case "Previous": currentPageNumber = Int32.Parse(lblCurrentPage.Text) - 1; break;
case "Next": currentPageNumber = Int32.Parse(lblCurrentPage.Text) + 1; break; }
BindData(); }
The ChangePage event is used to change the page number of the GridView and also to update the Label text by calling the BindData method.



www.svdeals.com super value deals

FormsAuthentication.SignOut Method (System.Web.Security) C# ASP 2.0

FormsAuthentication.SignOut Method (System.Web.Security): "FormsAuthentication.SignOut Method "


public void LoginLink_OnClick(object sender, EventArgs args)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}


www.svdeals.com super value deals

Login Control in C# ASP.NET 2.0

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>





Untitled Page








Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" />











Code

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
bool Authenticated = false;
Authenticated = SiteLevelCustomAuthenticationMethod(Login1.UserName, Login1.Password);
e.Authenticated = Authenticated;
if (Authenticated == true)
{
// Response.Redirect("Default.aspx");
}
}
private bool SiteLevelCustomAuthenticationMethod(string UserName, string Password)
{
bool boolReturnValue = false;
string strConnection = "server=xxxx;database=xxx_xxxx;uid=xxxx;pwd=xxx;Connect Timeout=60";
SqlConnection Connection = new SqlConnection(strConnection);
string strUserID = UserName;
String strSQL = "select * from UserDetails where UDUSRID=\'" + (strUserID + "\'");
SqlCommand command = new SqlCommand(strSQL, Connection);
SqlDataReader Dr;
Connection.Open();
Dr = command.ExecuteReader();
while (Dr.Read())
{
string UserNameDB = Dr["UDUSRID"].ToString();
string PasswordDB = Dr["UDPASSWD"].ToString();
if ((UserName == UserNameDB.TrimEnd().TrimStart()) & (Password == PasswordDB.TrimEnd().TrimStart()))
{
boolReturnValue = true;
break;
}
}
Dr.Close();
return boolReturnValue;
}
}


www.svdeals.com super value deals

How To: Protect Forms Authentication in ASP.NET 2.0

How To: Protect Forms Authentication in ASP.NET 2.0: "How To: Protect Forms Authentication in ASP.NET 2.0"

web.config

















www.svdeals.com super value deals

Forms Authentication in ASP.NET 2.0

Forms Authentication in ASP.NET 2.0: "Forms authentication"


www.svdeals.com super value deals

How to use Login Control in Visual Studio 2005

How to use Login Control in Visual Studio 2005: "How to use Login Control in Visual Studio 2005"



www.svdeals.com super value deals

Friday, May 4, 2007

Microsoft navigation menu frame

Microsoft navigation menu frame: "Chapter 7 - Migrating Oracle Databases to SQL Server 2000"



www.svdeals.com super value deals

Thursday, May 3, 2007

sp_spaceused (Transact-SQL)

sp_spaceused (Transact-SQL): "sp_spaceused (Transact-SQL) "

sp_spaceused [[ @objname = ] 'objname' ] [,[ @updateusage = ] 'updateusage' ]



www.svdeals.com super value deals

Microsoft SQL Server 2000 Analysis Services Performance Guide

Microsoft SQL Server 2000 Analysis Services Performance Guide: "Microsoft SQL Server 2000 Analysis Services Performance Guide"


www.svdeals.com super value deals

MySQL AB :: MySQL 5.0 Reference Manual :: 13.2.4.3 INSERT ... ON DUPLICATE KEY UPDATE Syntax

MySQL AB :: MySQL 5.0 Reference Manual :: 13.2.4.3 INSERT ... ON DUPLICATE KEY UPDATE Syntax

INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;UPDATE table SET c=c+1 WHERE a=1;


www.svdeals.com super value deals

MySQL AB :: MySQL 5.0 Reference Manual :: 13.2.4 INSERT Syntax

MySQL AB :: MySQL 5.0 Reference Manual :: 13.2.4 INSERT Syntax

INSERT [LOW_PRIORITY DELAYED HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ({expr DEFAULT},...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]



www.svdeals.com super value deals

Wednesday, May 2, 2007

GridView Paging - MSDN Forums

GridView Paging - MSDN Forums: "GridView Paging "
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}

private DataTable getTable()
{
SqlConnection conn = new SqlConnection("Data source=localhost;user id=user;password=pass;database=ClassProject");
SqlDataAdapter adap = new SqlDataAdapter("Select * from lessons", conn);
DataTable dt = new DataTable();
adap.Fill(dt);
return dt;
}

private void bind()
{
DataTable dr = getTable();
GridView1.DataSource = dr;
GridView1.DataBind();
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
}

How to populate DataGridView, GridView with SQL statement in C# - The Code Project - ASP.NET

How to populate DataGridView, GridView with SQL statement in C# - The Code Project - ASP.NET: "How to populate DataGridView, GridView with SQL statement in C#"

protected void Page_Load(object sender, EventArgs e)
{

string strSQLconnection = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("select * from table1", sqlConnection);
sqlConnection.Open();

SqlDataReader reader = sqlCommand.ExecuteReader();

GridView1.DataSource = reader;
GridView1.DataBind();
}

http://www.svdeals.com/ super value deals

Themes and Skins in ASP.NET 2.0 - The Code Project - ASP.NET

Themes and Skins in ASP.NET 2.0 - The Code Project - ASP.NET: "Themes and Skins in ASP.NET 2.0"



www.svdeals.com super value deals

Themes and Skins in ASP.NET 2.0 - The Code Project - ASP.NET

Themes and Skins in ASP.NET 2.0 - The Code Project - ASP.NET
Introduction
Themes in ASP.NET 2.0 is another cool new feature added to the plethora of additions and improvements made into the next version of the programming model. Using themes, you can easily customize your server controls with the pre-defined looks bundled with the .NET Framework or can make your own themes according to the look and feel of your website. Designing a website was never this easy before.
What are themes
Themes are introduced in ASP.NET 2.0 to counter the troubles faced by developers to define the layout of server controls and make them look coherent to the overall application, with minimum possible efforts. Default or Global themes are contained in a special folder inside the framework and can be declared in the source as well as class files. However, custom made themes can also be saved inside the predefined "App_Themes" folder inside ASP.NET applications, making them easier to manage and interpolate according to your needs. The essential part of themes are skin files with .skin extension. Besides skin files, a theme can be composed of styles sheets .css files as well as images for added support for the layout of the website.
Global themes
Built-in themes are saved in a special location under the installation path of the .NET Framework 2.0:
[Editor coment: Line breaks used to avoid scrolling.]%SystemRoot%\Microsoft.NET\Framework\VX.X.XXXX\
ASP.NETClientFiles\Themes\
The actual name of the subdirectory labeled vX.X.XXXX changes according to the build of ASP.NET 2.0 that you're considering. Themes defined in this path are visible to all applications running on the machine. However, ASP.NET 2.0 Beta 2 users will not find this folder in the specified location because ASP.NET team has dropped the Global Themes support from the beta 2 release of the product. But they will provide pre-defined themes as an add-on when Microsoft launches Visual Studio 2005 in November this year. These add-on themes can be purchased or downloaded separately and will be installed in the specified folder above.
How to apply themes
Themes can be used by a variety of methods. The following examples show you how you can define a theme named "SmokeAndGlass" in your application by different methods:<%@ Page Theme="SmokeAndGlass" Language="C#"%>
Themes can be set programmatically under the Page_PreInit event handler. It is necessary to define them in this event handler as all the looks are applied to the server controls defined in a particular theme before the page loads. Here is how you can set themes programmatically:protected void Page_PreInit(object sender, EventArgs e)
{
// Applying theme to a particular page
Page.Theme = "SmokeAndGlass";
}
Themes can also be stored in the web.config file which will be applied to the overall application. Themes declared in this file are therefore not required to be declared in any other file under the @Page tag.




Creating themes
You can create your own themes for applying to your site or individual pages. A page theme is defined in a special App_Themes folder under the root of a web application. In the page theme you define control skins - settings for individual controls such as Buttons, TextBoxes, hyperlinks and DataGrid etcetera. You typically define a control skin for each type of control that you want to use in your application and set the control properties so that all the controls have a similar look. However, note that themes configure only the visual properties of a control and does not alter their runtime behaviour. Here's is a typical example of a skin file:
CollapseFont-Size="0.9em" Font-Names="Verdana" />
BorderColor="#E7E5DB" BorderWidth="2" BackColor="#F8F7F4"
Font-Size=".9em" Font-Names="Verdana">
BorderColor="#585880" ForeColor="#585880" />
ForeColor="#CCCCCC" />
BackColor="transparent"
cssclass="theme_highlighted" />
ForeColor="#585880" BorderColor="#CCCCCC"
BorderWidth="1pt" cssclass="theme_header" />
BorderColor="transparent"
BackColor="transparent" />
BackColor="transparent" />
BackColor="#F8F7F4" />
ForeColor="#000000" BackColor="transparent" />
BackColor="Transparent" />

All global themes that were released with Beta 1 can be found inside the .zip sample application. These files can help you understand the skin files better.
Named skins
Skins without SkindID's are called default skins while skins with SkindID's are known as Named skins. Named skins define different layouts for two or more server controls with unique ID's. IDs can be defined in the same file or you can make different files with different ID's, it all depends on your personal approach and likings. SkinID can be referenced to call named skins. Here is an example:
Named skinsFont-Size="0.9em" Font-Names="Verdana" SkinID="LabelHeader" />
Font-Names="Arial" SkinID="LabelFooter" />
Referencing named skins

Dynamically applying themes
Themes can be dynamically applied to your application by adding a few lines of code. This will give users an option to select themes according to their taste. Here is an example showing you how to achieve this functionality:protected void Page_PreInit(object sender, EventArgs e)
{
string theme = ""; // setting the value to none
if (Page.Request.Form.Count > 0)
{
// "Themes" is the ID of dropdownlist
theme = Page.Request["Themes"].ToString();
if (theme == "Default")
{
theme = "";
}
}
this.Theme = theme; // applying themes to the overall page
}
All the controls defined in your Web Forms inherit the properties defined in the theme you select from the DropDownList with ID="Themes". You have to add all the global as well as custom made themes under the "App_Themes" folder in your application, the above mentioned example will not access themes inside the global themes folder.
Conclusion
ASP.NET 2.0 themes are somewhat identical to the Windows XP and Windows Server 2003 themes and provide skins for a variety of controls. Themes are the next big thing in styling after CSS style sheets. Themes can be manipulated programmatically unlike style sheets. All in all, ASP.NET 2.0 themes and skin files are a huge leap forward in providing the best styling experience for web developers in the shortest possible time.


www.svdeals.com super value deals

ASP.NET 2.0 CSS Friendly Control Adapters 1.0

ASP.NET 2.0 CSS Friendly Control Adapters 1.0: "ASP.NET 2.0 CSS Friendly Control Adapters 1.0"


www.svdeals.com super value deals

The Walkthrough: ASP.NET 2.0 CSS Friendly Control Adapters 1.0

The Walkthrough: ASP.NET 2.0 CSS Friendly Control Adapters 1.0: "ASP.NET 2.0 CSS Friendly Control Adapters: The Walkthrough"


www.svdeals.com super value deals

GridViewGuy What's up with Themes?"

GridViewGuy: "What's up with Themes?"

Hey! we got CSS (Cascading Style Sheets) so why do we need Themes? The thing about CSS is that it only exposes some fixed style properties which we can use. If we want to change some property like AlternatingItemStyle of the GridView control we will not be able to do this by using simple CSS. Themes allow you to change the control properties. This mean you can change most of the properties exposed by any server control in ASP.NET 2.0.

www.svdeals.com super value deals

Design Templates

Design Templates

Download these professionally designed Starter Kits and XHTML templates to get you started creating compelling, standards-compliant Web pages with ASP.NET 2.0. There are four Starter Kits below. These Starter Kits are complete web site solutions using ASP.NET’s latest controls (tree view control, grid view control, detail view control, login control, site map path controls and more). There are another 5 XHTML templates below. These are individual XHTML strict Web page templates (available each in two different colors) that are accompanied by design philosophy whitepapers that describe each template’s Section 508 conformance, page layout with CSS (page layouts using CSS floats or tables), Web page accessibility best practices and Web standard resources. All nine templates below are easily customizable and extendable to fit your own content.
For introduction to the ASP.NET Master Pages template set, click here.


www.svdeals.com super value deals

ASP.NET.4GuysFromRolla.com: Creating CSS Friendly Websites with ASP.NET 2.0

ASP.NET.4GuysFromRolla.com: Creating CSS Friendly Websites with ASP.NET 2.0: "Creating CSS Friendly Websites with ASP.NET 2.0"


www.svdeals.com super value deals

ScottGu's Blog : Tip/Trick: Use the ASP.NET 2.0 CSS Control Adapters for CSS friendly HTML output

ScottGu's Blog : Tip/Trick: Use the ASP.NET 2.0 CSS Control Adapters for CSS friendly HTML output: "Tip/Trick: Use the ASP.NET 2.0 CSS Control Adapters for CSS friendly HTML output"




www.svdeals.com super value deals

Monday, April 30, 2007

JDE Batch File - Order Transfer to Warehouse

Order Transfer to Warehouse
.BAT File
cd\
cd batfltrn
REM del R554268IT_DSM*.csv
move c:\batfltrn\R554268IT_DSM*.csv c:\batfltrn\backup
cd\
xcopy i:\PeopleSoft\ddp\e810\PrintQueue\R554268IT_DSM*.csv c:\batfltrn /d/m
ftp -s:c:/batfltrn/ccftp.txt




FILE Name: ccftp.txt

ftp
open xxxx.yyyyy.com (FTP Information)
zzzzzzz (User ID)
xxxxxx (Password)
cd in
lcd c:\batfltrn
binary
prompt n
mput R554268IT_ZJDE000*.CSV
quit


www.svdeals.com super value deals

MS-DOS move command help

MS-DOS move command help: "MOVE"


move c:\windows\temp\*.* c:\temp





www.svdeals.com super value deals

Saturday, April 28, 2007

FTP Error: 500 Invalid PORT Command

FTP Error: 500 Invalid PORT Command: "FTP Error: 500 Invalid PORT Command"

Tutorial 12: Using TemplateFields in the GridView Control

Tutorial 12: Using TemplateFields in the GridView Control: "Using TemplateFields in the GridView Control"

ASPdotNet Training
Tutorial 12: Using TemplateFields in the GridView Control

Scott Mitchell
February 2007
Download the code for this sample.
Contents of Tutorial 12 (Visual C#)
IntroductionStep 1: Binding the Data to the GridViewStep 2: Displaying the First and Last Names in a Single ColumnStep 3: Using the Calendar Control to Display the HireDate FieldStep 4: Showing the Number of Days the Employee Has Worked for the CompanyConclusionAbout the AuthorSpecial Thanks
Introduction
The GridView is composed of a set of fields that indicate what properties from the DataSource are to be included in the rendered output along with how the data will be displayed. The simplest field type is the BoundField, which displays a data value as text. Other field types display the data using alternate HTML elements. The CheckBoxField, for example, renders as a check box whose checked state depends on the value of a specified data field; the ImageField renders an image whose image source is based upon a specified data field. Hyperlinks and buttons whose state depends on an underlying data-field value can be rendered using the HyperLinkField and ButtonField field types, respectively.
While the CheckBoxField, ImageField, HyperLinkField, and ButtonField field types allow for an alternate view of the data, they still are fairly limited with respect to formatting. A CheckBoxField can display only a single check box, whereas an ImageField can display only a single image. What if a particular field must display some text, a check box, and an image, all based upon different data-field values? Or what if we wanted to display the data using a Web control other than the CheckBox, Image, HyperLink, or Button? Furthermore, the BoundField limits its display to a single data field. What if we wanted to show two or more data-field values in a single GridView column?
To accommodate this level of flexibility, the GridView offers the TemplateField, which renders using a template. A template can include a mix of static HTML, Web controls, and data-binding syntax. Furthermore, the TemplateField has a variety of templates that can be used to customize the rendering for different situations. For example, the ItemTemplate is used by default to render the cell for each row, but the EditItemTemplate template can be used to customize the interface when editing data.
In this tutorial, we'll examine how to use the TemplateField to achieve a greater degree of customization with the GridView control. In the preceding tutorial, we saw how to customize the formatting based on the underlying data using the DataBound and RowDataBound event handlers. Another way to customize the formatting based on the underlying data is by calling formatting methods from within a template. We'll look at this technique in this tutorial, too.
For this tutorial, we will use TemplateFields to customize the appearance of a list of employees. Specifically, we'll list all of the employees, but will display the employee's first and last names in one column, their hire dates in a Calendar control, and a status column that indicates how many days they've been employed at the company.

Figure 1. Three TemplateFields are used to customize the display. (Click on the picture for a larger image.)
Step 1: Binding the Data to the GridView
In reporting scenarios in which you must use TemplateFields to customize the appearance, I find it easier to start by creating a GridView control that contains just BoundFields first, and then add new TemplateFields or convert the existing BoundFields to TemplateFields, as needed. Therefore, let's start this tutorial by adding a GridView to the page through the Designer and binding it to an ObjectDataSource that returns the list of employees. These steps will create a GridView with a BoundField for each of the employee fields.
Open the GridViewTemplateField.aspx page, and drag a GridView from the Toolbox onto the Designer. From the GridView's smart tag, choose to add a new ObjectDataSource control that invokes the GetEmployees() method of the EmployeesBLL class.

Figure 2. Add a new ObjectDataSource control that invokes the GetEmployees() method. (Click on the picture for a larger image.)
Binding the GridView in this manner will automatically add a BoundField for each of the employee properties: EmployeeID, LastName, FirstName, Title, HireDate, ReportsTo, and Country. For this report, let's not bother with displaying the EmployeeID, ReportsTo, or Country property. To remove these BoundFields, you can:
Use the Fields dialog box. Click on the Edit Columns link from the GridView's smart tag to bring up this dialog box. Next, select the BoundFields from the lower-left list, and click the red X button to remove the BoundField.
Edit the GridView's declarative syntax by hand. From the Source view, delete the element for the BoundField that you want to remove.
After you have removed the BoundFields named EmployeeID, ReportsTo, and Country, your GridView's markup should look like the following:
Copy Code







Take a moment to view our progress in a browser. At this point, you should see a table with a record for each employee and four columns: one each for the employee's last name, first name, title, and hire date.

Figure 3. The LastName, FirstName, Title, and HireDate fields are displayed for each employee. (Click on the picture for a larger image.)
Step 2: Displaying the First and Last Names in a Single Column
Currently, each employee's first and last names are displayed in a separate column. It might be nice to combine them into a single column, instead. To accomplish this, we must use a TemplateField. We can either add a new TemplateField, add to it the needed markup and data-binding syntax, and then delete the BoundFields named FirstName and LastName, or we can convert the BoundFields named FirstName into a TemplateField, edit the TemplateField to include the LastName value, and then remove the BoundField named LastName.
Both approaches net the same result, but personally I like converting BoundFields to TemplateFields, when possible, because the conversion automatically adds an ItemTemplate and EditItemTemplate with Web controls and data-binding syntax to mimic the appearance and functionality of the BoundField. The benefit is that we'll need to do less work with the TemplateField, as the conversion process will have performed some of the work for us.
To convert an existing BoundField into a TemplateField, click on the Edit Columns link from the GridView's smart tag, which brings up the Fields dialog box. Select the BoundField to convert from the list in the lower-left corner, and then click the Convert this field into a TemplateField link in the bottom-right corner.

Figure 4. Convert a BoundField into a TemplateField from the Fields dialog box. (Click on the picture for a larger image.)
Go ahead and convert the BoundField named FirstName into a TemplateField. After this change, there's no perceptive difference in the Designer. This is because converting the BoundField into a TemplateField creates a TemplateField that maintains the look and feel of the BoundField. Despite there being no visual difference at this point in the Designer, this conversion process has replaced the BoundField's declarative syntax——with the following TemplateField syntax:
Copy Code

'>


'>


As you can see, the TemplateField consists of two templates: an ItemTemplate that has a Label whose Text property is set to the value of the FirstName data field, and an EditItemTemplate that has a TextBox control whose Text property also is set to the FirstName data field. The data-binding syntax—<%# Bind("fieldName") %>—indicates that the fieldName data field is bound to the specified Web control property.
To add the LastName data-field value to this TemplateField, we must add another Label Web control in the ItemTemplate and bind its Text property to LastName. This can be accomplished either by hand or through the Designer. To do it by hand, just add the appropriate declarative syntax to the ItemTemplate:
Copy Code

'>


'>
'>


To add it through the Designer, click on the Edit Templates link from the GridView's smart tag. This will display the GridView's template-editing interface. In this interface's smart tag is a list of the templates in the GridView. Because we have only one TemplateField at this point, the only templates listed in the drop-down list are those templates for the FirstName TemplateField, along with the EmptyDataTemplate and PagerTemplate. The EmptyDataTemplate template, if specified, is used to render the GridView's output if there are no results in the data bound to the GridView; the PagerTemplate, if specified, is used to render the paging interface for a GridView that supports paging.

Figure 5. The GridView's templates can be edited through the Designer. (Click on the picture for a larger image.)
To display also the LastName in the FirstName TemplateField, drag the Label control from the Toolbox into the ItemTemplate of the FirstName TemplateField in the GridView's template-editing interface.

Figure 6. Add a Label Web control to the FirstName TemplateField's ItemTemplate. (Click on the picture for a larger image.)
At this point, the Label Web control added to the TemplateField has its Text property set to Label. We must change this, so that this property is bound to the value of the LastName data field, instead. To accomplish this, click on the Label control's smart tag and choose the Edit DataBindings option.

Figure 7. Choose the Edit DataBindings option from the Label's smart tag. (Click on the picture for a larger image.)
This will bring up the DataBindings dialog box. From here, you can select the property to participate in data binding from the list on the left, and, from the drop-down list on the right, choose the field to which to bind the data. Choose the Text property from the left and the LastName field from the right, and click OK.

Figure 8. Bind the Text property to the LastName data field. (Click on the picture for a larger image.)
Note The DataBindings dialog box allows you to indicate whether to perform two-way data binding. If you leave this unchecked, the data-binding syntax <%# Eval("LastName")%>will be used, instead of <%# Bind("LastName")%>. Either approach is fine for this tutorial. Two-way data binding becomes important when inserting and editing data. For just displaying data, however, either approach will work equally well. We'll discuss two-way data binding in detail, in future tutorials.
Take a moment to view this page through a browser. As you can see, the GridView still includes four columns; however, the FirstName column now lists both the FirstName and LastName data-field values.

Figure 9. Both the FirstName and LastName values are shown in a single column. (Click on the picture for a larger image.)
To complete this first step, remove the LastName BoundField, and rename the HeaderText property of the FirstName TemplateField to "Name". After these changes, the GridView's declarative markup should look like the following:
Copy Code



'>


'>
'>







Figure 10. Each employee's first and last names are displayed in one column. (Click on the picture for a larger image.)
Step 3: Using the Calendar Control to Display the HireDate Field
Displaying a data-field value as text in a GridView is as easy as using a BoundField. For certain scenarios, however, the data is best expressed using a particular Web control instead of just text. Such customization of the display of data is possible with a TemplateField. For example, instead of displaying the employee's hire date as text, we could show a Calendar (using the Calendar control) with the employee's hire date highlighted.
To accomplish this, start by converting the BoundField named HireDate into a TemplateField. Just go to the GridView's smart tag and click the Edit Columns link, which brings up the Fields dialog box. Select the BoundField named HireDate, and click Convert this field into a TemplateField.

Figure 11. Convert the HireDate BoundField into a TemplateField. (Click on the picture for a larger image.)
As we saw in step 2, this will replace the BoundField with a TemplateField that contains an ItemTemplate and EditItemTemplate with a Label and TextBox whose Text properties are bound to the HireDate value using the data-binding syntax <%# Bind("HireDate")%>.
To replace the text with a Calendar control, edit the template by removing the Label and adding a Calendar control. From the Designer, select Edit Templates from the GridView's smart tag and, from the drop-down list, choose the ItemTemplate of the HireDate TemplateField. Next, delete the Label control, and drag a Calendar control from the Toolbox into the template-editing interface.

Figure 12. Add a Calendar control to the HireDate TemplateField's ItemTemplate. (Click on the picture for a larger image.)
At this point, each row in the GridView will contain a Calendar control in its HireDate TemplateField. However, the employee's actual HireDate value is not set anywhere in the Calendar control, which causes each Calendar control to default to showing the current month and date. To remedy this, we must assign each employee's HireDate to the Calendar control's SelectedDate and VisibleDate properties.
From the Calendar control's smart tag, choose Edit DataBindings. Next, bind both the SelectedDate and VisibleDate properties to the HireDate data field.

Figure 13. Bind the SelectedDate and VisibleDate properties to the HireDate data field. (Click on the picture for a larger image.)
Note The Calendar control's selected date does not necessarily have to be visible. For example, a Calendar might have August 1, 1999, as the selected date, but be showing the current month and year. The selected date and visible date are specified by the Calendar control's SelectedDate and VisibleDate properties. Because we want to both select the employee's HireDate and make sure that it's shown, we must bind both of these properties to the HireDate data field.
When viewing the page in a browser, the Calendar now shows the month of the employee's hired date and selects that particular date.

Figure 14. The employee's HireDate is shown in the Calendar control. (Click on the picture for a larger image.)
Note Contrary to all the examples we've seen thus far, for this tutorial we did not set the EnableViewState property to false for this GridView. The reason for this decision is that clicking the dates of the Calendar control causes a post-back, setting the Calendar's selected date to the date just clicked. If the GridView's view state is disabled, however, on each post-back, the GridView's data is rebound to its underlying data source, which causes the Calendar's selected date to be set back to the employee's HireDate, overwriting the date chosen by the user.
For this tutorial, this is a moot discussion, because the user is not able to update the employee's HireDate. It would probably be best to configure the Calendar control, so that its dates are not selectable. Either way, this tutorial shows that in some circumstances, view state must be enabled in order to provide certain functionality.
Step 4: Showing the Number of Days the Employee Has Worked for the Company
So far, we have seen two applications of TemplateFields:
Combining two or more data-field values into one column
Expressing a data-field value using a Web control instead of text
A third use of TemplateFields is in displaying metadata about the GridView's underlying data. In addition to showing the employees' hire dates, for example, we might also want to have a column that displays how many total days they've been on the job.
Yet another use of TemplateFields arises in scenarios in which the underlying data must be displayed differently in the Web page report from the format in which it's stored in the database. Imagine that the Employees table had a Gender field that stored the character M or F to indicate the gender of the employee. When displaying this information in a Web page, we might want to show the gender as either "Male" or "Female", as opposed to just "M" or "F".
Both of these scenarios can be handled by creating a formatting method in the ASP.NET page's code-behind class (or in a separate class library, implemented as a static method) that is invoked from the template. Such a formatting method is invoked from the template using the same data-binding syntax seen earlier. The formatting method can take in any number of parameters, but must return a string. This returned string is the HTML that is injected into the template.
To illustrate this concept, let's augment our tutorial to show a column that lists the total number of days an employee has been on the job. This formatting method will take in a Northwind.EmployeesRow object and return as a string the number of days that the employee has been employed. This method can be added to the ASP.NET page's code-behind class, but must be marked as protected or public in order to be accessible from the template.
Copy Codeprotected string DisplayDaysOnJob(Northwind.EmployeesRow employee)
{
// Make sure HireDate is not null... if so, return "Unknown"
if (employee.IsHireDateNull())
return "Unknown";
else
{
// Returns the number of days between the current
// date/time and HireDate
TimeSpan ts = DateTime.Now.Subtract(employee.HireDate);
return ts.Days.ToString("#,##0");
}
}
Because the HireDate field can contain NULL database values, we must first ensure that the value is not NULL before proceeding with the calculation. If the HireDate value is NULL, we just return the string "Unknown"; if it is not NULL, we compute the difference between the current time and the HireDate value, and return the number of days.
To utilize this method, we must invoke it from a TemplateField in the GridView using the data-binding syntax. Start by adding a new TemplateField to the GridView by clicking on the Edit Columns link in the GridView's smart tag and adding a new TemplateField.

Figure 15. Add a New TemplateField to the GridView. (Click on the picture for a larger image.)
Set the HeaderText property of this new TemplateField to Days on the Job and the HorizontalAlign property of its ItemStyle to Center. To call the DisplayDaysOnJob method from the template, add an ItemTemplate and use the following data-binding syntax:
Copy Code<%# DisplayDaysOnJob((Northwind.EmployeesRow) (System.Data.DataRowView) Container.DataItem).Row) %>
Container.DataItem returns a DataRowView object that corresponds to the DataSource record bound to the GridViewRow. Its Row property returns the strongly typed Northwind.EmployeesRow, which is passed to the DisplayDaysOnJob method. This data-binding syntax can appear directly in the ItemTemplate (as shown in the declarative syntax that follows) or it can be assigned to the Text property of a Label Web control.
Note Alternatively, instead of passing in an EmployeesRow instance, we could just pass in the HireDate value using <%# DisplayDaysOnJob(Eval("HireDate")) %>. However, the Eval method returns an object, so we would have to change our DisplayDaysOnJob method signature to accept an input parameter of type object, instead. We can't blindly cast the Eval("HireDate") call to a DateTime, because the HireDate column in the Employees table can contain NULL values. Therefore, we would have to accept an object as the input parameter for the DisplayDaysOnJob method, check to see if it had a database NULL value (which can be accomplished by using Convert.IsDBNull(objectToCheck)), and then proceed accordingly.
Because of these subtleties, I've opted to pass in the entire EmployeesRow instance. In the next tutorial we'll see a more fitting example for using the Eval("columnName") syntax for passing an input parameter into a formatting method.
The following shows the declarative syntax for our GridView after the TemplateField has been added and the DisplayDaysOnJob method called from the ItemTemplate:
Copy Code



'>


'>
'>





'>


'>VisibleDate='<%# Eval("HireDate") %>'>





<%# DisplayDaysOnJob((Northwind.EmployeesRow)((System.Data.DataRowView) Container.DataItem).Row) %>





Figure 16 shows the completed tutorial, when viewed through a browser.

Figure 16. Number of days employee has been on the job (Click on the picture for a larger image)
Conclusion
The TemplateField in the GridView control allows for a higher degree of flexibility in displaying data than is available with the other field controls. A TemplateField is ideal for situations in which:
Multiple data fields must be displayed in one GridView column.
The data is best expressed using a Web control, instead of plain text.
The output depends on the underlying data, such as displaying metadata or in reformatting the data.
In addition to customizing the display of data, a TemplateField is used also for customizing the user interfaces used for editing and inserting data, as we'll see in future tutorials.
The next two tutorials continue exploring templates, starting with a look at using TemplateFields in a DetailsView. Following that, we'll turn to the FormView, which uses templates instead of fields to provide greater flexibility in the layout and structure of the data.
Happy programming!
About the Author
Scott Mitchell, author of six ASP/ASP.NET books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies since 1998. Scott works as an independent consultant, trainer, and writer, and he recently completed his latest book, Sams Teach Yourself ASP.NET 2.0 in 24 Hours. He can be reached at mitchell@4guysfromrolla.com or via his blog, which can be found at http://scottonwriting.net/.
Special Thanks
This tutorial series was reviewed by many helpful reviewers. Lead reviewer for this tutorial was Dan Jagers. Interested in reviewing my upcoming MSDN articles? If so, drop me a line at mitchell@4GuysFromRolla.com.