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