Tuesday, October 4, 2011

Display Images In GridView From DataBase C# VB.NET

 Download sample code attached 
Sample code for displaying Images in Multiple columns

In this example i am showing how to display images in GridView from DataBase in ASP.NET using C#.NET and VB.NET or showing images stored in SQL Server database in gridview,For this i've already stored images in Database.

Table schema is shown below, ID column is primary key with Identity increment,datatype of Image column is Image.

Publish Post









For displaying images in gridview we need to create a Handler to read binary data from database.
Right click on solution explorer and Add new item, Pick Generic Handler and name it Handler.ashx.
Write this code in ProcessRequest method

C# code behind
01<%@ WebHandler Language="C#" Class="Handler" %>
02 
03using System;
04using System.Web;
05using System.Configuration;
06using System.Data.SqlClient;
07 
08public class Handler : IHttpHandler {
09 
10public void ProcessRequest (HttpContext context)
11{
12SqlConnection con = new SqlConnection();
13con.ConnectionString = ConfigurationManager.ConnectionStrings
14                      ["ConnectionString"].ConnectionString;
15 
16// Create SQL Command
17SqlCommand cmd = new SqlCommand();
18cmd.CommandText = "Select ImageName,Image from Images" +
19                  " where ID =@ID";
20cmd.CommandType = System.Data.CommandType.Text;
21cmd.Connection = con;
22 
23SqlParameter ImageID = new SqlParameter
24                    ("@ID", System.Data.SqlDbType.Int);
25ImageID.Value = context.Request.QueryString["ID"];
26cmd.Parameters.Add(ImageID);
27con.Open();
28SqlDataReader dReader = cmd.ExecuteReader();
29dReader.Read();
30context.Response.BinaryWrite((byte[])dReader["Image"]);
31dReader.Close();
32con.Close();
33}

VB.NET Code

01Public Class Handler
02    Implements IHttpHandler
03 
04Public Sub ProcessRequest(ByVal context As HttpContext)
05Dim con As New SqlConnection()
06con.ConnectionString = ConfigurationManager.ConnectionStrings
07                        ("ConnectionString").ConnectionString
08 
09        ' Create SQL Command
10 
11        Dim cmd As New SqlCommand()
12        cmd.CommandText = "Select ImageName,Image from Images" +
13                          " where ID =@IID"
14        cmd.CommandType = System.Data.CommandType.Text
15        cmd.Connection = con
16 
17        Dim ImageID As New SqlParameter
18                             ("@IID", System.Data.SqlDbType.Int)
19        ImageID.Value = context.Request.QueryString("ID")
20        cmd.Parameters.Add(ImageID)
21        con.Open()
22        Dim dReader As SqlDataReader = cmd.ExecuteReader()
23        dReader.Read()
24        context.Response.BinaryWrite
25                    (DirectCast(dReader("Image"), Byte()))
26        dReader.Close()
27        con.Close()
28    End Sub
29End Class
Now drag a GridView control on the aspx page and add SQLDataSource to it.


Now go to html markup of GridView and add a TemplateField and in ItemTemplate add a Image control to display Images.
Html Source of GridView should look like this

<asp:GridView ID="GridView1" runat="server" 
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
InsertVisible="False" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName"
SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [ImageName], [Image]
FROM [Images]"
></asp:SqlDataSource>


For VB.NET there is slight change in html markup of page
change below mentioned line
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>


to


ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")%>'/>

THis is how it will look

If you want to display Images in multiple columns or in more than one clumns of GridView then u need to make changes in the code as mentioned below.

1. Add a new column in database (i've named it Image2)
2. Add one mote Template Field in html source of gridview and change source as below
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=1"%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image2">
<ItemTemplate>
<asp:Image ID="Image2" runat="server"
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=2"%>'/>
</ItemTemplate>
</asp:TemplateField>

And make these changes in code behind of handler.ashx
01//Add this line of code in handler.ashx
02int intImg = Convert.ToInt32(context.Request.QueryString["img"]);
03//Now change earlier code to this one
04SqlDataReader dReader = cmd.ExecuteReader();
05        dReader.Read();
06        if (intImg == 1)
07        {
08            context.Response.BinaryWrite((byte[])dReader["Image"]);
09        }
10        else if (intImg == 2)
11        {
12            context.Response.BinaryWrite((byte[])dReader["Image2"]);
13        }
14        dReader.Close();
15        con.Close();
Now it will look like this


hope this helps.

3:17 AM by Dilip kakadiya · 0

Display image gallery in ASP.NET GridView Control








 DownLoad Code

 Introduction

In this article I will try to explain you how you can display images as a gallery view using GridView control of ASP.NET.
I face problem of paging when I had tried it with DataList control. In DataList we can define repeat column direction to display images as gallery. But main problem is paging, and you have to use third party control to apply paging in DataList and it is difficult to manage with third party control.
But here I have taken GridView control to display image gallery. With use of internal paging. So we can done all operation very simply on GridView control.
Lets Start.

1. Code for .ASPX page is as follow

<asp:GridView ID="gvListProperty" runat="server" AutoGenerateColumns="false" Width="100%"
border="0" AllowPaging="true" BorderColor="white" cssClass="griditem" PageSize="10" >
<PagerSettings Mode="Numeric" Position="TopAndBottom"/>
<PagerStyle CssClass="mypager" HorizontalAlign="right" />
<Columns>
<asp:TemplateField>
<HeaderStyle CssClass="dispnone" />
<ItemTemplate>
<table width="100%">
<tr>
<td class="bdr-grey">
<table width="100%" border="0" cellspacing="0" cellpadding="0" Class="griditem" >
<tr>
<td width="60px" height="60px" Class="griditem" >
<%#Container.DataItem("Column1")%>
</td>
<td width="60px" height="60px" Class="griditem" >
<%#Container.DataItem("Column2")%>
</td>
<td width="60px" height="60px" Class="griditem" >
<%#Container.DataItem("Column3")%>
</td>
<td width="60px" height="60px" Class="griditem" >
<%#Container.DataItem("Column4")%>
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here we have taken Gridview control named by “gvListProperty”. In this GridView control I have taken one template column. So in that we can apply some formatting as we want to display.
You can also apply some CSS to table inside this template column. Here we have set AllowPaging=True. Because we need to use paging in this gallery view. This GridView will display 40 records on each page. Here I have set pageSize=10 so it has fix page size to display records only 40*10=400. You can change it as per your requirement.
Paging mode is numeric and page number will display on Top and Bottom of the GridView.
First column is 4 static column noted with bold face.
Now look at <%#Container.DataItem("Column1")%>, <%#Container.DataItem("Column2")%>, <%#Container.DataItem("Column3")%>, <%#Container.DataItem("Column4")%>.
These columns I have define are not related to Database Table columns. The data will fillup in this column from code behind. Because I face problem to display images as repeat column manner. This is possible in DataList only to display record in repeat column direction. But here in GridView Control it is not possible. And same in DataList control internal paging is not possible.

2. Code behind operations.

Declaring object variable

Here you can simplify code by writing it in a region section. Declare object variable first in a code behind file. (before page load)
#Region " Data Members "
Dim objPropertyForSale As New Propertyforsale
#End Region
Variable objPropertyForSale is a object of class Propertyforsale.vb class file. In propertyforsale.vb you can write method to fetch data from database table.

Call function that retrive records from database

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)_
Handles Me.Load
If Not IsPostBack Then

'To set page nuber after redirecting back from detail page
If Request.QueryString("iPn") <> Nothing Or IsNumeric(Request.QueryString("iPn")) Then

gvListProperty.PageIndex = CInt(Request.QueryString("iPn"))

End If

'Call function that retrieve records from database
Call BindPropertyGallery()
End If
End Sub
In a page load event I am calling function that will retrieve records form table.
Here is code for this function.
Public Sub BindPropertyGallery()
Dim dsProperty As DataSet
With objPropertyForSale
dsProperty = .Galleryview_PropertyList()
If dsProperty.Tables(0).Rows.Count > 0 Then

'Integrate this record with DataTable and then bind it with GridView

Call DataTableBind(dsProperty)
End If
End With
End Sub
Galleryview_PropertyList function is written in class file propertyforSale.vb. This function will retrive records and return DataSet.
Function DataTableBind will bind this records with gridview columns.
Look below code that is written in propertyforSale.vb class file.
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports commonlib

Public Class Propertyforsale
Dim DM As New commonlib.DBManager(ConfigurationManager.ConnectionStrings(
"ConnectionString").ConnectionString)
Dim sSql As String
Dim retVal As New DataSet
#Region "Method"

Public Function Gallaryview_PropertyList() As DataSet
sSql = "Gallaryview_PropertyList"
retVal = DM.ExecuteDataSet(CommandType.StoredProcedure, sSql)
Return retVal
End Function
#End Region
End Class
This is a sample code written in class file. I have created my own DBManager file, that is used for performing all DB operation. You can use DataAdepter or DataReader to do same in code behind file.
Classfile function Gallaryview_PropertyList() is returning value as DataSet. sSql is representing procedure name that used to retrive records. retVal dataset will return records back to codebehind file from where this function is called.
Now come back to code behind file operation.

Integrate this record with DataTable and then bind it with GridView

Read this code very carefully because all display and paging logic is dependent on this code. I face too much problem when writing code first time. It has taken too much time to write this simple code.
This is lengthy but very simple code.
Here I have used DataTable to insert each image in its 4 columns one by one. After 4 columns have data it will generate new row with new 4 columns and same way it rotating up to last record of the Dataset.
Public Sub DataTableBind(ByVal dsProperty As DataSet)
'-- Paging Variables --'
'Due to Paging Counter == 40 Records per page
Dim iCountIncre As Integer = 40 ' Records per page
Dim iPn As Integer = 0 'Current Page Number
'-- End Paging Variables --'

Dim iCount As Integer
Dim iColumn As Integer = 1
Dim dtTable As New DataTable
Dim dtCol As DataColumn
Dim dtRow As DataRow

dtCol = New DataColumn("Column1")
dtTable.Columns.Add(dtCol)
dtCol = New DataColumn("Column2")
dtTable.Columns.Add(dtCol)
dtCol = New DataColumn("Column3")
dtTable.Columns.Add(dtCol)
dtCol = New DataColumn("Column4")
dtTable.Columns.Add(dtCol)
dtRow = dtTable.NewRow
For iCount = 0 To dsProperty.Tables(0).Rows.Count - 1

'Due to Paging Counter == 40 Records per page, On Every 40 records Page number will get increment.
If (iCount + 1) > iCountIncre Then
iCountIncre = iCountIncre + 40
iPn = iPn + 1
End If

dtRow("Column" & iColumn) = "<a href='fulladdforrent.aspx?iPn=" & iPn.ToString & _
"&QCD=GLV&QID=" & dsProperty.Tables(0).Rows(iCount).Item("iPropertyID") & _
"' class='txt-grey'> <img src='../Images/Property/thumb/" & _
dsProperty.Tables(0).Rows(iCount).Item("sImageName") & _
"' border='0' alt='Vis'/>"

'This will maintain 4 columns per row.
iColumn = iColumn + 1

'This will maintain 4 columns per row. When column get number 5, at that time it
'turns for new row
If iColumn = 5 Then
dtTable.Rows.Add(dtRow)
dtRow = dtTable.NewRow
iColumn = 1
End If

If iCount = dsProperty.Tables(0).Rows.Count - 1 And iColumn <= 5 Then
dtTable.Rows.Add(dtRow)
dtRow = dtTable.NewRow
End If
Next

'Add table to the dataset
Dim ds As New DataSet

ds.Tables.Add(dtTable)

'Now GridView get ds(dataset) as DataSource
gvListProperty.DataSource = ds
gvListProperty.DataBind()
End Sub
In a function DataTableBind I have passed a dataset with records. Here I have taken variable dtTable of type DataTable. As explain early. dtTable has 4 columns DataColumn("Column1") to DataColumn("Column4"). If you can’t getting why I have taken this then again look at column description of GridView control explain early on.
For Loop with iCount will run up to last record of the dataset.
Variable iCountIncre will get increment of value 40 at every 40 records so we can manage page number consistency. This is why because we have to pass current page number of browsed image gallery page to its detail page. And when returning back from detail page to gallery view at that time we have to maintain this page number.
Variable iColumn is used to maintain column consistency from column no.1 to 4. Because here we have to display 4 images at each row.
dtRow("Column" & iColumn) = "<a href='fulladdforrent.aspx?iPn=" & iPn.ToString & "&QID=" &_
dsProperty.Tables(0).Rows(iCount).Item("iPropertyID") &_
"' class='txt-grey'> <img src='../Images/Property/thumb/" &_
dsProperty.Tables(0).Rows(iCount).Item("sImageName") &_
"' border='0' alt='View'/>"
In this logic dtRow(“Column” & iColumn) will be like this dtRow(“Column1”) and upto dtRow(“Column4”).
So this dtRow has Column and that column value will display image in gallery because it call that image from path with image name from database table dsProperty.Tables(0).Rows(iCount).Item("sImageName").
And link on that image represent the link page name with iPn (page number), iPropertyID (because image is related to that property. It represent unique id of property).
ds.Tables.Add(dtTable) 
And after that bind this table with dataset “ds”. And bind this dataset “ds” to GridView.
Following code is used to manage paging of GridView control.
Protected Sub gvListProperty_PageIndexChanging(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) & _
Handles gvListProperty.PageIndexChanging
gvListProperty.PageIndex = e.NewPageIndex
Call BindPropertyGallary()
End Sub
When user click on any page number it will call this event and code written inside this event will change the current page index and assign new page number to GridView and bind this GridView again with record. After binding GridView the page which you see it is of new assign page number.

One more thing I want to share with you that is I also got suggestion to bind this GridView in RowDataBound Event of the GridView. To bind this GridView in RowDataBound we have to take Record Dataset either Public Variable or in a ViewState and then need to do some extra operation then as I wrote in function DataTableBind(). So Dataset with records in Public Variable or with ViewState will occupy more memory compare to existing code memory usage. That's why I had let go that concept.

3:14 AM by Dilip kakadiya · 0

Using Parameterized Queries with the SqlDataSource

Introduction

In the previous tutorial we saw how to use the SqlDataSource control to retrieve data directly from a database. Using the Configure Data Source wizard, we could choose the database and then either: pick the columns to return from a table or view; enter a custom SQL statement; or use a stored procedure. Whether selecting columns from a table or view or entering a custom SQL statement, the SqlDataSource control s SelectCommand property is assigned the resulting ad-hoc SQL SELECT statement and it is this SELECT statement that is executed when the SqlDataSource s Select() method is invoked (either programmatically or automatically from a data Web control).
The SQL SELECT statements used in the previous tutorial s demos lacked WHERE clauses. In a SELECT statement, the WHERE clause can be used to limit the results returned. For example, to display the names of products costing more than $50.00, we could use the following query:
SELECT ProductName FROM Products WHERE UnitPrice > 50.00 Typically, the values used in a WHERE clause are determine by some external source, such as a querystring value, a session variable, or user input from a Web control on the page. Ideally, such inputs are specified through the use of parameters. With Microsoft SQL Server, parameters are denoted using @parameterName, as in:
SELECT ProductName FROM Products WHERE UnitPrice > @Price The SqlDataSource supports parameterized queries, both for SELECT statements and INSERT, UPDATE, and DELETE statements. Moreover, the parameter values can be automatically pulled from a variety of sources the querystring, session state, controls on the page, and so on or can be assigned programmatically. In this tutorial, we ll see how to define parameterized queries as well as how to specify the parameter values both declaratively and programmatically.
Note: In the previous tutorial we compared the ObjectDataSource which has been our tool of choice over the first 46 tutorials with the SqlDataSource, noting their conceptual similarities. These similarities also extend to parameters. The ObjectDataSource s parameters mapped to the input parameters for the methods in the Business Logic Layer. With the SqlDataSource, the parameters are defined directly within the SQL query. Both controls have collections of parameters for their Select(), Insert(), Update(), and Delete() methods, and both can have these parameter values populated from pre-defined sources (querystring values, session variables, and so on) or assigned programmatically.

Creating a Parameterized Query

The SqlDataSource control s Configure Data Source wizard offers three avenues for defining the command to execute to retrieve database records:
  • By picking the columns from an existing table or view,
  • By entering a custom SQL statement, or
  • By choosing a stored procedure
When picking columns from an existing table or view, the parameters for the WHERE clause must be specified through the Add WHERE Clause dialog box. When creating a custom SQL statement, however, you can enter the parameters directly into the WHERE clause (using @parameterName to denote each parameter). A stored procedure consists of one or more SQL statements, and these statements can be parameterized. The parameters used in the SQL statements, however, must be passed in as input parameters to the stored procedure.
Since creating a parameterized query depends on how the SqlDataSource s SelectCommand is specified, let s take a look at all three approaches. To get started, open the ParameterizedQueries.aspx page in the SqlDataSource folder, drag a SqlDataSource control from the Toolbox onto the Designer, and set its ID to Products25BucksAndUnderDataSource. Next, click the Configure Data Source link from the control s smart tag. Select the database to use (NORTHWINDConnectionString) and click Next.

Step 1: Adding a WHERE Clause When Picking the Columns from a Table or View

When selecting the data to return from the database with the SqlDataSource control, the Configure Data Source wizard allows us to simply pick the columns to return from an existing table or view (see Figure 1). Doing so automatically builds up a SQL SELECT statement, which is what is sent to the database when the SqlDataSource s Select() method is invoked. As we did in the previous tutorial, select the Products table from the drop-down list and check the ProductID, ProductName, and UnitPrice columns.
Pick the Columns to Return from a Table or View
Figure 1: Pick the Columns to Return from a Table or View (Click to view full-size image)
&nbsp;
To include a WHERE clause in the SELECT statement, click the WHERE button, which brings up the Add WHERE Clause dialog box (see Figure 2). To add a parameter to limit the results returned by the SELECT query, first choose the column to filter the data by. Next, choose the operator to use for filtering (=, <, <=, >, and so on). Finally, choose the source of the parameter s value, such as from the querystring or session state. After configuring the parameter, click the Add button to include it in the SELECT query.
For this example, let s only return those results where the UnitPrice value is less than or equal to $25.00. Therefore, pick UnitPrice from the Column drop-down list and <= from the Operator drop-down list. When using a hard-coded parameter value (such as $25.00) or if the parameter value is to be specified programmatically, select None from the Source drop-down list. Next, enter the hard-coded parameter value in the Value textbox 25.00 and complete the process by clicking the Add button.
Limit the Results Returned from the Add WHEREClause Dialog Box
Figure 2: Limit the Results Returned from the Add WHERE Clause Dialog Box (Click to view full-size image)
&nbsp;
After adding the parameter, click OK to return to the Configure Data Source wizard. The SELECT statement at the bottom of the wizard should now include a WHERE clause with a parameter named @UnitPrice:
SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products] WHERE ([UnitPrice] <= @UnitPrice)
Note: If you specify multiple conditions in the WHERE clause from the Add WHERE Clause dialog box, the wizard joins them with the AND operator. If you need to include an OR in the WHERE clause (such as WHERE UnitPrice <= @UnitPrice OR Discontinued = 1) then you have to build the SELECT statement through the custom SQL statement screen.
Complete configuring the SqlDataSource (click Next, then Finish) and then inspect the SqlDataSource s declarative markup. The markup now includes a <SelectParameters> collection, which spells out the sources for the parameters in the SelectCommand.

<asp:SqlDataSource ID="Products25BucksAndUnderDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>" SelectCommand= "SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products] WHERE ([UnitPrice] <= @UnitPrice)"> <SelectParameters> <asp:Parameter DefaultValue="25.00" Name="UnitPrice" Type="Decimal" /> </SelectParameters> </asp:SqlDataSource>
 
When the SqlDataSource s Select() method is invoked, the UnitPrice parameter value (25.00) is applied to the @UnitPrice parameter in the SelectCommand before being sent to the database. The net result is that only those products less than or equal to $25.00 are returned from the Products table. To confirm this, add a GridView to the page, bind it to this data source, and then view the page through a browser. You should only see those products listed that are less than or equal to $25.00, as Figure 3 confirms.
Only Those Products Less Than or Equal to $25.00 are Displayed
Figure 3: Only Those Products Less Than or Equal to $25.00 are Displayed (Click to view full-size image)
&nbsp;

Step 2: Adding Parameters to a Custom SQL Statement

When adding a custom SQL statement you can enter the WHERE clause explicitly or specify a value in the Filter cell of the Query Builder. To demonstrate this, let s display just those products in a GridView whose prices are less than a certain threshold. Start by adding a TextBox to the ParameterizedQueries.aspx page to collect this threshold value from the user. Set the TextBox s ID property to MaxPrice. Add a Button Web control and set its Text property to Display Matching Products .
Next, drag a GridView onto the page and from its smart tag choose to create a new SqlDataSource named ProductsFilteredByPriceDataSource. From the Configure Data Source wizard, proceed to the Specify a custom SQL statement or stored procedure screen (see Figure 4) and enter the following query:
SELECT ProductName, UnitPrice FROM Products WHERE UnitPrice <= @MaximumPrice OR @MaximumPrice = -1.0 After entering the query (either manually or through the Query Builder), click Next.
Return Only Those Products Less Than or Equal to a ParameterValue
Figure 4: Return Only Those Products Less Than or Equal to a Parameter Value (Click to view full-size image)
&nbsp;
Since the query includes parameters, the next screen in the wizard prompts us for the source of the parameters values. Choose Control from the Parameter source drop-down list and MaxPrice (the TextBox control s ID value) from the ControlID drop-down list. You can also enter an optional default value to use in the case where the user has not entered any text into the MaxPrice TextBox. For the time being, do not enter a default value.
The MaxPrice TextBox s Text Property is Used as the Parameter Source
Figure 5: The MaxPrice TextBox s Text Property is Used as the Parameter Source (Click to view full-size image)
&nbsp;
Complete the Configure Data Source wizard by clicking Next, then Finish. The declarative markup for the GridView, TextBox, Button, and SqlDataSource follows:

Maximum price: $<asp:TextBox ID="MaxPrice" runat="server" Columns="5" /> <asp:Button ID="DisplayProductsLessThanButton" runat="server" Text="Display Matching Products" /> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="ProductsFilteredByPriceDataSource" EnableViewState="False"> <Columns> <asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" /> <asp:BoundField DataField="UnitPrice" HeaderText="Price" HtmlEncode="False" DataFormatString="{0:c}" SortExpression="UnitPrice" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="ProductsFilteredByPriceDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>" SelectCommand= "SELECT ProductName, UnitPrice FROM Products WHERE UnitPrice <= @MaximumPrice"> <SelectParameters> <asp:ControlParameter ControlID="MaxPrice" Name="MaximumPrice" PropertyName="Text" /> </SelectParameters> </asp:SqlDataSource>

 
Note that the parameter within the SqlDataSource s <SelectParameters> section is a ControlParameter, which includes additional properties like ControlID and PropertyName. When the SqlDataSource s Select() method is invoked, the ControlParameter grabs the value from the specified Web control property and assigns it to the corresponding parameter in the SelectCommand. In this example, the MaxPrice s Text property is used as the @MaxPrice parameter value.
Take a minute to view this page through a browser. When first visiting the page or whenever the MaxPrice TextBox lacks a value no records are displayed in the GridView.
No Records are Displayed When the MaxPriceTextBox is Empty
Figure 6: No Records are Displayed When the MaxPrice TextBox is Empty (Click to view full-size image)
&nbsp;
The reason no products are shown is because, by default, an empty string for a parameter value is converted into a database NULL value. Since the comparison of [UnitPrice] <= NULL always evaluates as False, no results are returned.
Enter a value into the textbox, like 5.00, and click the Display Matching Products button. On postback, the SqlDataSource informs the GridView that one of its parameter sources has changed. Consequently, the GridView rebinds to the SqlDataSource, displaying those products less than or equal to $5.00.
Products Less Than or Equal to $5.00 are Displayed
Figure 7: Products Less Than or Equal to $5.00 are Displayed (Click to view full-size image)
&nbsp;

Initially Displaying All Products

Rather than displaying no products when the page is first loaded, we may want to display all products. One way to list all products whenever the MaxPrice TextBox is empty is to set the parameter s default value to some insanely high value, like 1000000, since it s unlikely that Northwind Traders will ever have inventory whose unit price exceeds $1,000,000. However, this approach is shortsighted and might not work in other situations.
In previous tutorials - Declarative Parameters and Master/Detail Filtering With a DropDownList we were faced with a similar problem. Our solution there was to put this logic in the Business Logic Layer. Specifically, the BLL examined the incoming value and, if it was NULL or some reserved value, the call was routed to the DAL method that returned all records. If the incoming value was a normal filtering value, a call was made to the DAL method that executed a SQL statement that used a parameterized WHERE clause with the supplied value.
Unfortunately, we bypass the architecture when using the SqlDataSource. Instead, we need to customize the SQL statement to intelligently grab all records if the @MaximumPrice parameter is NULL or some reserved value. For this exercise, let s have it so that if the @MaximumPrice parameter is equal to -1.0, then all of the records are to be returned (-1.0 works as a reserved value since no product can have a negative UnitPrice value). To accomplish this we can use the following SQL statement:
SELECT ProductName, UnitPrice FROM Products WHERE UnitPrice <= @MaximumPrice OR @MaximumPrice = -1.0 This WHERE clause returns all records if the @MaximumPrice parameter equals -1.0. If the parameter value is not -1.0, only those products whose UnitPrice is less than or equal to the @MaximumPrice parameter value are returned. By setting the default value of the @MaximumPrice parameter to -1.0, on the first page load (or whenever the MaxPrice TextBox is empty), @MaximumPrice will have a value of -1.0 and all products will be displayed.
Now All Products are Displayed When the MaxPriceTextBox is Empty
Figure 8: Now All Products are Displayed When the MaxPrice TextBox is Empty (Click to view full-size image)
&nbsp;
There are a couple of caveats to note with this approach. First, realize that the parameter s data type is inferred by it s usage in the SQL query. If you change the WHERE clause from @MaximumPrice = -1.0 to @MaximumPrice = -1 , the runtime treats the parameter as an integer. If you then attempt to assign the MaxPrice TextBox to a decimal value (like 5.00 ), an error will occur because it cannot convert 5.00 to an integer. To remedy this, either make sure that you use @MaximumPrice = -1.0 in the WHERE clause or, better yet, set the ControlParameter object s Type property to Decimal .
Secondly, by adding the OR @MaximumPrice = -1.0 to the WHERE clause, the query engine cannot use an index on UnitPrice (assuming one exists), thereby resulting in a table scan. This can impact performance if there are a sufficiently large number of records in the Products table. A better approach would be to move this logic to a stored procedure where an IF statement would either perform a SELECT query from the Products table without a WHERE clause when all records need to be returned or one whose WHERE clause contains just the UnitPrice criteria, so that an index can be used.

Step 3: Creating and Using Parameterized Stored Procedures

Stored procedures can include a set of input parameters that can then be used in the SQL statement(s) defined within the stored procedure. When configuring the SqlDataSource to use a stored procedure that accepts input parameters, these parameter values can be specified using the same techniques as with ad-hoc SQL statements.
To illustrate using stored procedures in the SqlDataSource, let s create a new stored procedure in the Northwind database named GetProductsByCategory, which accepts a parameter named @CategoryID and returns all of the columns of the products whose CategoryID column matches @CategoryID. To create a stored procedure, go to the Server Explorer and drill down into the NORTHWND.MDF database. (If you don t see the Server Explorer, bring it up by going to the View menu and selecting the Server Explorer option.)
From the NORTHWND.MDF database, right-click on the Stored Procedures folder, choose Add New Stored Procedure , and enter the following syntax:
CREATE PROCEDURE dbo.GetProductsByCategory ( @CategoryID int ) AS SELECT * FROM Products WHERE CategoryID = @CategoryID Click the Save icon (or Ctrl+S) to save the stored procedure. You can test the stored procedure by right-clicking it from the Stored Procedures folder and choosing Execute. This will prompt you for the stored procedure s parameters (@CategoryID, in this instance), after which the results will be displayed in the Output window.
The GetProductsByCategory StoredProcedure when Executed with a @CategoryID of 1
Figure 9: The GetProductsByCategory Stored Procedure when Executed with a @CategoryID of 1 (Click to view full-size image)
&nbsp;
Let s use this stored procedure to display all products in the Beverages category in a GridView. Add a new GridView to the page and bind it to a new SqlDataSource named BeverageProductsDataSource. Continue to the Specify a custom SQL statement or stored procedure screen, select the Stored procedure radio button, and pick the GetProductsByCategory stored procedure from the drop-down list.
Select the GetProductsByCategoryStored Procedure from the Drop-Down List
Figure 10: Select the GetProductsByCategory Stored Procedure from the Drop-Down List (Click to view full-size image)
&nbsp;
Since the stored procedure accepts an input parameter (@CategoryID), clicking Next prompts us to specify the source for this parameter s value. The Beverages CategoryID is 1, so leave the Parameter source drop-down list at None and enter 1 into the DefaultValue textbox.
Use a Hard-Coded Value of 1 to Return the Products in theBeverages Category
Figure 11: Use a Hard-Coded Value of 1 to Return the Products in the Beverages Category (Click to view full-size image)
&nbsp;
As the following declarative markup shows, when using a stored procedure, the SqlDataSource s SelectCommand property is set to the name of the stored procedure and the SelectCommandType property is set to StoredProcedure, indicating that the SelectCommand is the name of a stored procedure rather than an ad-hoc SQL statement.

<asp:SqlDataSource ID="BeverageProductsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>" SelectCommand="GetProductsByCategory" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:Parameter DefaultValue="1" Name="CategoryID" Type="Int32" /> </SelectParameters> </asp:SqlDataSource>
 
Test out the page in a browser. Only those products that belong to the Beverages category are displayed, although all of the product fields are displayed since the GetProductsByCategory stored procedure returns all of the columns from the Products table. We could, of course, limit or customize the fields displayed in the GridView from the GridView s Edit Columns dialog box.
All of the Beverages are Displayed
Figure 12: All of the Beverages are Displayed (Click to view full-size image)
&nbsp;

Step 4: Programmatically Invoking a SqlDataSource s Select() Statement

The examples we ve seen in the previous tutorial and this tutorial so far have bound SqlDataSource controls directly to a GridView. The SqlDataSource control s data, however, can be programmatically accessed and enumerated in code. This can be particularly useful when you need to query data to inspect it, but don t need to display it. Rather than having to write all of the boilerplate ADO.NET code to connect to the database, specify the command, and retrieve the results, you can let the SqlDataSource handle this monotonous code.
To illustrate working with the SqlDataSource s data programmatically, imagine that your boss has approached you with a request to create a web page that displays the name of a randomly selected category and its associated products. That is, when a user visits this page, we want to randomly choose a category from the Categories table, display the category name, and then list the products belonging to that category.
To accomplish this we need two SqlDataSource controls one to grab a random category from the Categories table and another to get the category s products. We ll build the SqlDataSource that retrieves a random category record in this step; Step 5 looks at crafting the SqlDataSource that retrieves the category s products.
Start by adding a SqlDataSource to ParameterizedQueries.aspx and set its ID to RandomCategoryDataSource. Configure it so that it uses the following SQL query:
SELECT TOP 1 CategoryID, CategoryName FROM Categories ORDER BY NEWID() ORDER BY NEWID() returns the records sorted in random order (see Using NEWID() to Randomly Sort Records). SELECT TOP 1 returns the first record from the result set. Put together, this query returns the CategoryID and CategoryName column values from a single, randomly selected category.
To display the category s CategoryName value, add a Label Web control to the page, set its ID property to CategoryNameLabel, and clear out its Text property. To programmatically retrieve the data from a SqlDataSource control, we need to invoke its Select() method. The Select() method expects a single input parameter of type DataSourceSelectArguments, which specifies how the data should be messaged before being returned. This can include instructions on sorting and filtering the data, and is used by the data Web controls when sorting or paging through the data from a SqlDataSource control. For our example, though, we don t need the data to be modified before being returned, and therefore will pass in the DataSourceSelectArguments.Empty object.
The Select() method returns an object that implements IEnumerable. The precise type returned depends on the value of the SqlDataSource control s DataSourceMode property. As discussed in the previous tutorial, this property can be set to a value of either DataSet or DataReader. If set to DataSet, the Select() method returns a DataView object; if set to DataReader, it returns an object that implements IDataReader. Since the RandomCategoryDataSource SqlDataSource has its DataSourceMode property set to DataSet (the default), we will be working with a DataView object.
The following code illustrates how to retrieve the records from the RandomCategoryDataSource SqlDataSource as a DataView as well as how to read the CategoryName column value from the first DataView row:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load ' Get the data from the SqlDataSource as a DataView Dim randomCategoryView As DataView = CType _ (RandomCategoryDataSource.Select(DataSourceSelectArguments.Empty), DataView) If randomCategoryView.Count > 0 Then ' Assign the CategoryName value to the Label CategoryNameLabel.Text = String.Format( _ "Here are Products in the {0} Category...", _ randomCategoryView(0)("CategoryName").ToString()) End If End Sub randomCategoryView(0) returns the first DataRowView in the DataView. randomCategoryView(0)("CategoryName") returns the value of the CategoryName column in this first row. Note that the DataView is loosely-typed. To reference a particular column value we need to pass in the name of the column as a string ( CategoryName , in this case). Figure 13 shows the message displayed in the CategoryNameLabel when viewing the page. Of course, the actual category name displayed is randomly selected by the RandomCategoryDataSource SqlDataSource on each visit to the page (including postbacks).
The Randomly Selected Category s Name is Displayed
Figure 13: The Randomly Selected Category s Name is Displayed (Click to view full-size image)
&nbsp;
Note: If the SqlDataSource control s DataSourceMode property had been set to DataReader, the return value from the Select() method would have needed to be cast to IDataReader. To read the CategoryName column value from the first row, we d use code like:
If randomCategoryReader.Read() Then Dim categoryName as String = randomCategoryReader("CategoryName').ToString() ... End If With the SqlDataSource randomly selecting a category, we re ready to add the GridView that lists the category s products.
Note: Rather than using a Label Web control to display the category s name, we could have added a FormView or DetailsView to the page, binding it to the SqlDataSource. Using the Label, however, allowed us to explore how to programmatically invoke the SqlDataSource s Select() statement and work with its resulting data in code.

Step 5: Assigning Parameter Values Programmatically

All of the examples we ve seen so far in this tutorial have used either a hard-coded parameter value or one taken from one of the pre-defined parameter sources (a querystring value, a Web control on the page, and so on). However, the SqlDataSource control s parameters can also be set programmatically. To complete our current example, we need a SqlDataSource that returns all of the products belonging to a specified category. This SqlDataSource will have a CategoryID parameter whose value needs to be set based on the CategoryID column value returned by the RandomCategoryDataSource SqlDataSource in the Page_Load event handler.
Start by adding a GridView to the page and bind it to a new SqlDataSource named ProductsByCategoryDataSource. Much like we did in Step 3, configure the SqlDataSource so that it invokes the GetProductsByCategory stored procedure. Leave the Parameter source drop-down list set to None , but do not enter a default value, as we will set this default value programmatically.
Do Not Specify a Parameter Source or Default Value
Figure 14: Do Not Specify a Parameter Source or Default Value (Click to view full-size image)
&nbsp;
After completing the SqlDataSource wizard, the resulting declarative markup should look similar to the following:

<asp:SqlDataSource ID="ProductsByCategoryDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>" SelectCommand="GetProductsByCategory" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:Parameter Name="CategoryID" Type="Int32" /> </SelectParameters> </asp:SqlDataSource>

 
We can assign the DefaultValue of the CategoryID parameter programmatically in the Page_Load event handler:
' Assign the ProductsByCategoryDataSource's ' CategoryID parameter's DefaultValue property ProductsByCategoryDataSource.SelectParameters("CategoryID").DefaultValue = _ randomCategoryView(0)("CategoryID").ToString() With this addition, the page includes a GridView that shows the products associated with the randomly selected category.
Do Not Specify a Parameter Source or Default Value
Figure 15: Do Not Specify a Parameter Source or Default Value (Click to view full-size image)
&nbsp;

Summary

The SqlDataSource enables page developers to define parameterized queries whose parameter values can be hard-coded, pulled from pre-defined parameter sources, or assigned programmatically. In this tutorial we saw how to craft a parameterized query from the Configure Data Source wizard for both ad-hoc SQL queries and stored procedures. We also looked at using hard-coded parameter sources, a Web control as a parameter source, and programmatically specifying the parameter value.
Like with the ObjectDataSource, the SqlDataSource also provides capabilities to modify its underlying data. In the next tutorial we ll look at how to define INSERT, UPDATE, and DELETE statements with the SqlDataSource. Once these statements have been added, we can utilize the built-in inserting, editing, and deleting features inherent to the GridView, DetailsView, and FormView controls.

3:09 AM by Dilip kakadiya · 0

ASP.NET MVC 3: Layouts with Razor


Two weeks ago we shipped the ASP.NET MVC 3 Beta Release.  It supports “go live” deployments, and includes a bunch of nice improvements/enhancements.  You can see a summary of the new ASP.NET MVC 3 features in my beta announcement post.  Also read my original ASP.NET MVC 3 Preview post to learn about other ASP.NET MVC 3 features that showed up with that initial preview release.
This is another in a series of “mini-posts” I’m doing that talk about a few of the new ASP.NET MVC 3 Beta features in more detail:

In today’s post I’m going to discuss layout pages with Razor, and discuss some of the improvements to them that we introduced with the recent ASP.NET MVC 3 Beta.

Razor Basics

ASP.NET MVC 3 ships with a new view-engine option called “Razor” (in addition to continuing to support/enhance the existing .aspx view engine).
You can learn more about Razor, why we are introducing it, and the syntax it supports from my Introducing Razor blog post.  If you haven’t read that post yet, take a few minutes and read it now (since the rest of this post will assume you have read it). Once you’ve read the Introducing Razor post, also read my ASP.NET MVC 3 Preview post and look over the ASP.NET MVC 3 Razor sample I included in it.

What are Layouts?

You typically want to maintain a consistent look and feel across all of the pages within your web-site/application.  ASP.NET 2.0 introduced the concept of “master pages” which helps enable this when using .aspx based pages or templates.  Razor also supports this concept with a feature called “layouts” – which allow you to define a common site template, and then inherit its look and feel across all the views/pages on your site.

Using Layouts with Razor

In my last blog post I walked through a simple example of how to implement a /Products URL that renders a list of product categories:
image_thumb_1263F129[1]
Below is a simple ProductsController implementation that implements the /Products URL above.  It retrieves a list of product categories from a database, and then passes them off to a view file to render an appropriate HTML response back to the browser:
image_thumb_579C4852[1]
Here is what the Index.cshtml view file (implemented using Razor) looks like:
image_thumb_17A2B20D[1]
The above view file does not yet use a layout page – which means that as we add additional URLs and pages to the site we’ll end up duplicating our core site layout in multiple places.  Using a layout will allow us to avoid this duplication and make it much easier to manage our site design going forward.  Let’s update our sample to use one now.
Refactoring to use a Layout
Razor makes it really easy to start from an existing page and refactor it to use a layout.  Let’s do that with our simple sample above.  Our first step will be to add a “SiteLayout.cshtml” file to our project under the \Views\Shared folder of our project (which is the default place where common view files/templates go):
image
SiteLayout.cshtml
We’ll use the SiteLayout.cshtml file to define the common content of our site.  Below is an example of what it might look like:
image
A couple of things to note with the above file:
  • It is no longer necessary (as of the ASP.NET MVC 3 Beta) to have an @inherits directive at the top of the file. You can optionally still have one if you want (for example: if you want a custom base class), but it isn’t required.  This helps keep the file nice and clean.  It also makes it easier to have designers and non-developers work on the file and not get confused about concepts they don’t understand.
  • We are calling the @RenderBody() method within the layout file above to indicate where we want the views based on this layout to “fill in” their core content at that location in the HTML.
  • We are outputting the “View.Title” property within the <title> element of our <head> section.  I’ll discuss how this is used in a bit.
And now we have a common layout template that we can use to maintain a consistent look and feel across any number of pages on our site.
Index.cshtml
Let’s now update our Index.cshtml view to be based on the SiteLayout.cshtml file we just created.  Below is an first-cut of what it might look like:
image
A couple of things to note about the above file:
  • We did not need to wrap our main body content within a tag or element – by default Razor will automatically treat the content of Index.cshtml as the “body” section of the layout page.  We can optionally define “named sections” if our layout has multiple replaceable regions.  But Razor makes the 90% case (where you only have a body section) super clean and simple.
  • We are programmatically setting the View.Title value within our Index.cshtml page above.  The code within our Index.cshtml file will run before the SiteLayout.cshtml code runs – and so we can write view code that programmatically sets values we want to pass to our layout to render.  This is particularly useful for things like setting the page’s title, as well as <meta> elements within the <head> for search engine optimization (SEO).
  • At the moment, we are programmatically setting the Layout template to use within our Index.cshtml page.  We can do this by setting the Layout property on the View (note: in the first preview this property was called “LayoutPage” – we changed it to just be “Layout” with the ASP.NET MVC 3 Beta).  I’ll discuss some alternative ways (new with the ASP.NET MVC 3 Beta) that we can set this property shortly.
And now when we request the /Products URL within our site, we’ll get the following HTML returned:
image
Notice above how the returned HTML content is a merge of the SiteLayout.cshtmk and Index.cshtml.  The “Product Categories” title at the top is set correctly based on the view, and our dynamic list of categories is populated in the correct place.

DRYing things up with _ViewStart

Currently we are programmatically setting the layout file to use at the top of our Index.cshtml file.  This is fine for cases where we have some view-specific logic where the layout file will vary depending on the specific view.  But setting it this way can end up being redundant and duplicative for most web applications – where either all of the views use the same layout, or if they have different layouts (for example: for mobile devices or localized sites) the logic for which layout to pick is common across all of the views.
The good news is that Razor (starting with the ASP.NET MVC 3 Beta release) includes a new feature that enables us to remove the need to explicitly set the Layout in each view – and instead allows us to define the layout logic once for all views in the site – making our view files even cleaner and more maintainable (and ensuring we keep to the DRY principle: Don’t Repeat Yourself):
image
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
image
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering.  For example, we could write code like below within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
image
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set.  For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops.  Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility.  It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Note: You can also specify layouts within a Controller or an Action Filter. So if you prefer to keep the layout selection logic there you can do that as well.

Finished Sample

Below is a screen-shot of the simple application we have been building:
image
Here is the ProductsControllers that implements the /Products URL and retrieves the categories from a database and passes them to a view template to render:
image_thumb_579C4852[1]
Here is the Index.cshtml view that we are using the render the /Products response:
image
Here is the SiteLayout.cshtml layout file we are using to implement a consistent look and feel across our site:
image
Here is the _ViewStart.cshtml file that we are using to specify that all views in our site by default use the SiteLayout.cshtml file:
image
And here is the generated HTML from the /Products URL:
image
And because we now have a common layout file for our site, we can build out more functionality, controllers and views within our application - and have a site UI experience that is both consistent and very easy to maintain.

More Advanced Stuff

Two common questions people often ask are:
1) Can I have nested layout files?
2) Can I have multiple, non-contiguous, replaceable regions within a layout file – so that I can “fill in” multiple different sections within my view files.
The answer to both of these questions is YES!  I’ll blog some samples of how to do this in the future.

Summary

As I’ve mentioned before, one of the themes we’ve focused on with the ASP.NET MVC 3 and Razor releases has been to make the code you write cleaner and more concise.  We think the new layout functionality coming with this release contributes nicely towards making view files even easier to read and write.  I’ll be covering other nice improvements like this that are new to the ASP.NET MVC 3 Beta in future posts.

2:55 AM by Dilip kakadiya · 0