ToolBox Data Control XmlDataSource

XmlDataSource Web Server Control

in ASP.NET environment,This article describes you how to work with XmlDataSource Web Control.The XmlDataSource control provides the way to binding data to data-bound controls using XML data. By using XmlDataSource Control in DOT.Net,You can display the data with view of both hierarchical and tabular, although the XmlDataSource control is typically used to display hierarchical XML data in read-only scenarios.

Retrieving Data Using the XmlDataSource Control

The XmlDataSource control represents the attributes of XML elements that means each node of Xml file as bindable columns.The XmlDataSource loads XML data from an XML file specified using the DataFile property. XML data can also be loaded from a string using the Data property. If you want to bind to values that are not attributes, you can specify a transformation using an Extensible Sylesheet Language (XSL) style sheet. In control templates, such as in a FormView or GridView controls, you can also bind a control in a template to XML data using the XPath data-binding function.

The following code snippets shows an XmlDataSource with a TreeView control

in .aspx file

<html  >
  <head id="Head1" runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form2" runat="server">
      <asp:XmlDataSource
        id="DS1"
        runat="server"
        DataFile="~/App_Data/smplXml.xml" />

      <asp:TreeView
        id="Tree1"
        runat="server"
        DataSourceID="DS1">
        <DataBindings>
          <asp:TreeNodeBinding DataMember="UserId"    TextField="#InnerText" />
          <asp:TreeNodeBinding DataMember="UserName"   TextField="#InnerText" />
        </DataBindings>
      </asp:TreeView>

    </form>
  </body>
</html>

in .xml file,

<?xml version="1.0" encoding="utf-8" ?>
<People>
  <Person>
    <Name>
      <UserName>Rock</UserName>
    </Name>
    <Address>
      <Street>345, Navin St.</Street>
      <City>Dallas</City>
      <Region>America</Region>
      <ZipCode>23652</ZipCode>
    </Address>
    <Job>
      <Title>PL</Title>
      <Description>Develops company strategies.</Description>
    </Job>
  </Person>

  <Person>
    <Name>
      <UserName>Sarfudeen</UserName>
    </Name>
    <Address>
      <Street>4 North St.</Street>
      <City>Banglore</City>
      <Region>IND</Region>
      <ZipCode>12365</ZipCode>
    </Address>
    <Job>
      <Title>Doctor</Title>
      <Description>Heart spl.</Description>
    </Job>
  </Person>
</People>                    
                    
 
Transforming XML Data Using the XmlDataSource Control

You must offer an XSL for the XmlDataSource control when you need transform the xml data at earlier to displayed it by Data-bound control such as Gridview,Detailsview... For XML data, you can loading the style sheet from a file which is exists in the application path, which you specify using the TransformFile property. However, you can also load the style sheet directly from a string using the Transform property.

The following code example shows an XmlDataSource and a TreeView control bound to it.

in .aspx file,

<html  >
  <head id="Head1" runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form2" runat="server">
      <asp:XmlDataSource
        id="DS1"
        runat="server"
        TransformFile="~/App_Data/smplXsl.xsl"
        DataFile="~/App_Data/smplXml.xml" />

      <asp:TreeView
        id="Tree1"
        runat="server"
        DataSourceID="DS1">
        <DataBindings>
          <asp:TreeNodeBinding DataMember="Name"   TextField="#InnerText" />
        </DataBindings>
      </asp:TreeView>

    </form>
  </body>
</html>                    
                    

in .xml file,

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="People">
  <Names>
    <xsl:apply-templates select="Person"/>
  </Names>
</xsl:template>

<xsl:template match="Person">
  <xsl:apply-templates select="Name"/>
</xsl:template>

<xsl:template match="Name">
  <name><xsl:value-of select="UserName"/>
</xsl:template>
</xsl:stylesheet>                   
                    
 
Editing XML Data Using the XmlDataSource Control

in DOT.Net environment,we can modify the XML data even which is displaying in a Data-bound control.because of The XmlDataSource control is commonly used in read-only data scenarios. Note that automatic update, insert, and delete operations that work with other data source controls will not work. You must write custom code to modify data using the XmlDataSource control.

Using GetXmlDocument method to retrieve an XmlDocument object, which is an in-memory representation of the XML data for edit the XML data.You make sure that the following restrictions when editing XML data using the XmlDataSource control:

  • The XML data must be loaded from an XML file specified with the DataFile property, and not from a string of XML specified in the Data property.
  • No XSLT transformation can be specified in the Transform or TransformFile properties.
  • The Save method does not handle concurrent save operations by different requests. If more than one user is editing an XML file using the XmlDataSource control, there is no guarantee that all users are operating with the same data, and no guarantee that one user will not overwrite changes from another user.
Filtering of XmlDataSource Control

By using XPath expression,you can filter the Xml data.Because, By default, the XmlDataSource control exposes all of the XML data specified by the DataFile or Data properties. However, The XPath property allows you to specify an XPath filter expression that is applied after XML data is loaded and has had any transformations applied to it.

Caching of XmlDataSource Control

By default, caching feature is enabled for the XmlDataSource control Because of avoiding the time consuming.opening and reading an XML file every time can affect the performance of your application. Therefore,Caching lets you reduce the processing load on your server at the expense of memory on the Web server;


Posted by: Admin
Posted on: 9/12/2009 at 2:25 PM
Tags: , ,
Categories: Asp.net
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (443) | Post RSSRSS comment feed

ToolBox Data Control SiteMapDataSource

SiteMapDataSource Web Server Control

in ASP.NET environment,This article describes you how to work with SiteMapDataSource Web Control.Normally, The SiteMapDataSource control can be used to represent the navigation path such as one to another page. The SiteMapDataSource Web server control retrieves navigation data from a site-map provider, and then passes the data to controls that can display that data, such as the TreeView and Menu controls.

This data includes information about the pages in your Web site, such as the URL, title, description, and location in the navigation hierarchy. Storing your navigation data in one place makes it easier to add and remove items in the navigational menus of your Web site.

Display Site-Map Data in Non-Hierarchical Web Server Controls

in DOT.Net environment,we are able to bind site-map data to non-hierarchical controls, such as the DropDownList, CheckBoxList that display data in a linear, or flat, format. Site-map data is inherently hierarchical, which means that each node can contain zero or more child nodes. The TreeView and Menu controls are designed to work with hierarchical data.

The following code snippets shows an DropDownList control to display the site-map data from a Web.sitemap file.

in .aspx.cs file

Public void _OnSelectedIndexChanged(ByVal Sender As Object, ByVal e As EventArgs)
    Response.Redirect(ddl1.SelectedItem.Value)
  End Sub

in .aspx file,

<body>
    <form id="form2" runat="server">
    <div>
      <asp:SiteMapDataSource ID="SMS1" Runat="Server"
          StartFromCurrentNode="true"
          ShowStartingNode="false" />
      <asp:DropDownList ID="ddl1" Runat="Server" 
          DataSourceID="SMS1"
          AutoPostBack="True" 
          DataTextField="Title" 
          DataValueField="Url"
          OnSelectedIndexChanged="_OnSelectedIndexChanged" >
      </asp:DropDownList>
    </div>
    </form>
</body>
                   
                    
 
Add Simple Site Navigation

By Using SiteMapPath, TreeView, or Menu controls, users can easily understand the navigation path of your Web site. A Simple Navigation path of SiteMapPath looks like as:

Home > Profile > Contact

To create a Web.sitemap file
  • Create a file in the root directory of your Web site called Web.sitemap.
  • Open the Web.sitemap file and add the following code.
<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
  <siteMapNode title="Home" >
    <siteMapNode title="Profile" >
      <siteMapNode title="Contact" url="~/Contact.aspx"/>
    </siteMapNode>
  </siteMapNode>
</siteMap>           
                    
  • Save your file and then close it.
To add site navigation to a Web page
  • Create a file in the root directory of your Web site called Training.aspx.
  • Open Training.aspx and add the following code.
<html  >
<head id="Head1" runat="server">
  <title>Example Navigation</title>
</head>
<body>
  <form id="form2" runat="server">
  <div>

  <h2>Using SiteMapPath</h2>
  <asp:SiteMapPath ID="SMP1" Runat="server">
  </asp:SiteMapPath>


  <asp:SiteMapDataSource ID="SMS1" Runat="server" />

  <h2>Using TreeView</h2>
  <asp:TreeView ID="Tree1" Runat="Server" DataSourceID="SMS1">
  </asp:TreeView>

  <h2>Using Menu</h2>
  <asp:Menu ID="Menu2" Runat="server" DataSourceID="SMS1">
  </asp:Menu>
  
  <h2>Using a Horizontal Menu</h2>
  <asp:Menu ID="Menu1" Runat="server" DataSourceID="SMS1"
    Orientation="Horizontal" 
    StaticDisplayLevels="2" >
  </asp:Menu>
  
  </div>
  </form>
</body>
</html>                 
                    
  • Save and close the file.now you run and make sure the output.

Posted by: Admin
Posted on: 9/12/2009 at 2:24 PM
Tags: , , ,
Categories: Asp.net
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (98) | Post RSSRSS comment feed

ToolBox Data Control ObjectDataSource

ObjectDataSource Web Server Control

in ASP.NET environment,This article describes you how to work with ObjectDataSource Web Control.The ASP.NET ObjectDataSource control allows the user to get the capablities of retrieval and update data using a middle-tier object.

in DOT.Net environment, The ObjectDataSource control serves as a data interface for data-bound controls such as the GridView, FormView, or DetailsView controls, and enables those controls to display and edit data from a middle-tier business object on an ASP.NET Web page.

Receive and Modify Data

In DOT.Net environment,The ObjectDataSource control can be supporting for a three-tier architecture by providing a way for you to bind data controls on the page to a middle-tier business object. The ObjectDataSource works with a middle-tier business object to select, insert, update, delete, page, sort, cache, and filter data declaratively without extensive code.

Most ASP.NET data source controls, such as the SqlDataSource, are used in a two-tier application architecture where the presentation layer (the ASP.NET Web page) communicates directly with the data tier (the database, an XML file, and so on).

For Selecting, updating, inserting and deleting the data,The ObjectDataSource control uses reflection to call methods of a business object. You set the ObjectDataSource control's TypeName property to specify the name of the class to use as a source object.

Sorting and Paging

Sorting and Paging features has been provided with advanced by the ObjectDataSource control with the requests from a data-bound control, such as a GridView control, to the data object for processing. The source data object or the data source control itself can then sort data and return data in pages.

Caching of ObjectDataSource

by using Business object,the ObjectDataSource control can cache objects returned from them. However, you should not cache objects that hold resources or that maintain state that cannot be shared among multiple requests, such as an open DataReader object.

Filtering of ObjectDataSource

when the ObjectDataSource control receive any object of Dataset or DataTable,then the ObjectDataSource control supports filtering using the syntax of the Expression property of the DataColumn class. Filtering enables you to expose only rows that match particular search criteria, without having to re-query the data source with new selection criteria. For more information, see Filtering Data Using Data Source Controls.

Conflict Detection

When change the ObjectDataSource control's ConflictDetection property to true, you can specify that the ObjectDataSource control should include original values when calling update methods of the source data object. The original values can then be included in checks for optimistic concurrency.

To Creating a Data-Access Component
  • Create app_code folder in your application path
  • Right-click the App_Code folder, and then click Add New Item.
  • Under Visual Studio installed templates, click DataSet.
  • In the Name box, type yourObjectName, and then click Add.
  • Click New Connection and provide your connection information such as servername,and so on
  • Click Next.
  • Select the Yes, save this connection as check box, and then click Next.
  • Click Use SQL statements, and then click Next.
  • Under What data should be loaded into the table, type as: Select * from Table1
  • Click to clear the Fill a DataTable check box, and then select the Return a DataTable and Create methods to send updates directly to the database check boxes.
  • In the Method Name box, type Yourmethod.
  • Click Finish.
  • On the Build menu, click Build Web Site to make sure that the component compiles correctly.
To add a data source control to the page
  • go to Design view.
  • From the Data group in the Toolbox, drag an ObjectDataSource control onto the page.
  • On the ObjectDataSource Tasks shortcut menu, click Configure Data Source.
  • In the Choose your business object list, select your tableadapter.This is the type name (namespace and class name)
  • Click Next.
  • On the Select tab, in the Choose a method list, click MethodName(), returns DataTable.
  • Click Finish.
To add a GridView control to the page and bind it to the data
  • From the Data group in the Toolbox, drag a GridView control onto the page.
  • On the GridView Tasks shortcut menu, in the Choose Data Source list, click ObjectDataSource1, which is created by you
  • In Properties, verify that the DataKeyNames is set to yourcolumn.

  • Posted by: Admin
    Posted on: 9/12/2009 at 2:22 PM
    Tags: , ,
    Categories: Asp.net
    Actions: E-mail | Kick it! | DZone it! | del.icio.us
    Post Information: Permalink | Comments (138) | Post RSSRSS comment feed

    ToolBox Data Control AccessDataSource

    AccessDataSource Web Server Control

    in ASP.NET environment,This article describes you how to work with AccessDataSource Web Control.By using AccessDataSource control, we are able to working with Microsoft Access databases.The AccessDataSource control using SQL queries to manipulating the data from database to your desired application.This control is very similar to the SqlDataSource control except that you do not set the ConnectionString property.

    Instead of provide the Connectionstring,you simply set the location of the Access .mdb file, using the DataFile property, and the AccessDataSource takes care of the underlying connection to the database. You should place Access databases in the App_Data directory of the Web site and reference them by a relative path (for example, ~/App_Data/DB1.mdb). This location offers additional security for data files, because they are not served if they are requested directly by the client Web browser.

    Features of AccessDataSource
    • Sorting - Set the DataSourceMode property to the DataSet value.
    • Filtering - Set the FilterExpression property to a filtering expression used to filter the data when the Select method is called.
    • Paging - The AccessDataSource does not support direct paging operations on an Access database. A data-bound control, such as the GridView, can page over the items returned by the AccessDataSource, if the DataSourceMode property is set to the DataSet value.
    • Updating - Set the UpdateCommand property to a SQL statement used to update data. This statement is typically parameterized.
    • Deleting - Set the DeleteCommand property to a SQL statement used to delete data. This statement is typically parameterized.
    • Inserting - Set the InsertCommand property to a SQL statement used to insert data. This statement is typically parameterized.
    • Caching - Set the DataSourceMode property to the DataSet value, the EnableCaching property to true, and the CacheDuration and CacheExpirationPolicy properties according to the caching behavior you want for your cached data.
    Get Data Using the AccessDataSource

    After including the AccessDataSource control on your page,then the Next step is to Bind the Data using AccessDataSource control.By using the AccessDataSource control,we can gathering data from a Microsoft Access database (.mdb file).Now, You can display the data in data-bound controls, such as the GridView, FormView, and DetailsView controls.

    Connecting to a Database using the AccessDataSource Control

    for this purpose,using the DataFile property of the AccessDataSource control that connects to the Microsoft Access database file (.mdb file) where according to specified what in the DataFile property. You can set the DataFile property to a universal naming convention (UNC) path that points to an Access database file.

    The following code snippets represents the AccessDatasource connects to a DataBase.

      <asp:AccessDataSource
        id="AccessDataSource1"
        DataFile="~/App_Data/DB1.mdb"
        runat="server"
        SelectCommand="SELECT * FROM Table1">
      </asp:AccessDataSource>
                      
     
    Select Data By AccessDataSource Control

    The following code snippets helps you to retrieving Data from Database using AccessDataSource Control,

    <html>
      <asp:AccessDataSource
        id="AccessDataSource1"
        DataFile="~/App_Data/DB1.mdb"
        runat="server"
        SelectCommand="SELECT * FROM Table1" />
    
      <asp:GridView
        id="EmployeesGridView"
        runat="server"
        AutoGenerateColumns="True"
        DataSourceid="AccessDataSource1" />
    </html>    
                      
     
    Parameters Vs AccessDataSource Control

    You can send the parameter values to the ASP.NET data source controls at run time, in ASP.NET environment, the AccessDataSource control accept the parameter value includes via SQL Queries. You can use parameters to supply search criteria for data retrieval; to supply values to be inserted, updated, or deleted in a data store; and to supply values for sorting, paging, and filtering. Using parameters enables you to filter data.

    Similarly,another Data Souce controls such as SqlDataSource can accept the parameterized values. For example, the SqlDataSource and AccessDataSource controls allow you to specify parameter placeholders in an SQL statement, such as the SelectCommand

    The following code example shows a SqlDataSource control that uses parameterized commands to query and modify data from a data-bound control. Parameters are explicitly specified in order to strongly type parameter values and to specify output parameters.

    Parameter Types
    • ControlParameter - Sets a parameter to the property value of a Control on an ASP.NET Web page. You specify the Control using the ControlID property. You specify the name of the property that supplies the parameter value using the ControlParameter object's PropertyName property.
    • CookieParameter - Sets a parameter to the value of an HttpCookie object. You specify the name of the HttpCookie object using the CookieName property. If the specified HttpCookie object does not exist, then the value of the DefaultValue property is used as the parameter value.
    • FormParameter -Sets a parameter to the value of an HTML form field. You specify the name of the HTML form field using the FormField property. If the specified HTML form field value does not exist, then the value of the DefaultValue property is used as the parameter value.
    • ProfileParameter -Sets a parameter to the value of a property from the current user profile ( Profile). You specify the name of the profile property using the PropertyName property. If the specified profile property does not exist, then the value of the DefaultValue property is used as the parameter value.
    • QueryStringParameter - Sets a parameter to the value of a QueryString field. You specify the name of the QueryString field using the QueryStringField property. If the specified QueryString field does not exist, then the value of the DefaultValue property is used as the parameter value.
    • SessionParameter - Sets a parameter to the value of a Session object. You specify the name of the Session object using the SessionField property. If the specified Session object does not exist, then the value of the DefaultValue property is used as the parameter value.

    in .aspx.cs page,

    void ddl1_OnSelectedIndexChanged(Object sender, EventArgs e)
      {
        DV1.DataBind();
      }
    
      void DV1_ItemUpdated(Object sender, DetailsViewUpdatedEventArgs e)
      {
        ddl1.DataBind();
        ddl1.SelectedValue = e.Keys["UserId"].ToString();
        DV1.DataBind();
      }
      
      void DV1_ItemDeleted(Object sender, DetailsViewDeletedEventArgs e)
      {
        ddl1.DataBind();
      }
    
      void SDS1_OnInserted(Object sender, SqlDataSourceStatusEventArgs e)
      {
        System.Data.Common.DbCommand command = e.Command;   
        ddl1.DataBind();
        ddl1.SelectedValue = 
          command.Parameters["@prmId"].Value.ToString();
        DV1.DataBind();
      }
                       
                        

    in .aspx page,

    <html>
    <head id="Head1" runat="server">
        <title>User Details</title>
    </head>
    <body>
        <form id="form2" runat="server">
            <h3>
                User Details</h3>
            <table cellspacing="10">
                <tr>
                    <td valign="top">
                        <asp:DropDownList ID="ddl1" DataSourceID="SDS1"
     DataValueField="UserId" DataTextField="UserName"
                            AutoPostBack="True" OnSelectedIndexChanged=
    "ddl1_OnSelectedIndexChanged" runat="Server" />
                    </td>
                    <td valign="top">
                        <asp:DetailsView ID="DV1" DataSourceID="SDS2"
     AutoGenerateRows="false" AutoGenerateInsertButton="true"
                            AutoGenerateEditButton="true" AutoGenerateDeleteButton=
    "true" DataKeyNames="UserId"
                            GridLines="Both" OnItemUpdated="DV1_ItemUpdated" 
    OnItemDeleted="DV1_ItemDeleted"
                            runat="server">
                            <HeaderStyle BackColor="Navy" ForeColor="White" />
                            <RowStyle BackColor="White" />
                            <AlternatingRowStyle BackColor="Blue" />
                            <EditRowStyle BackColor="Gray" />
                            <Fields>
                                <asp:BoundField DataField="UserId" 
    HeaderText="User ID" InsertVisible="False" ReadOnly="true" />
                                <asp:BoundField DataField="UserName" 
    HeaderText="User Name" />
                            </Fields>
                        </asp:DetailsView>
                    </td>
                </tr>
            </table>
    <asp:SqlDataSource ID="SDS1" SelectCommand="SELECT UserId, UserName FROM Table1"
    ConnectionString="<%$ ConnectionStrings:connstr %>" 
    runat="server"></asp:SqlDataSource>
            <asp:SqlDataSource ID="SDS2" SelectCommand="SELECT *
                             FROM Employees WHERE UserId = @prmId"
     InsertCommand="INSERT INTO Table1(UserName)
                             VALUES (@UserName); 
                             SELECT @prmId = SCOPE_IDENTITY()"
     UpdateCommand="UPDATE Table1 SET UserName=@UserName
                             WHERE UserId=@UserId" DeleteCommand="DELETE Table1
     WHERE UserId=@UserId"
                ConnectionString="<%$ ConnectionStrings:Connstr %>"
     OnInserted="SDS1_OnInserted"
                runat="server">
                <SelectParameters>
                    <asp:ControlParameter ControlID="ddl1" 
    PropertyName="SelectedValue" Name="prmId"
                        Type="Int32" DefaultValue="0" />
                </SelectParameters>
                <InsertParameters>
                    <asp:Parameter Name="UserName" Type="String" />
                    <asp:Parameter Name="prmId" Direction="Output" Type="Int32" 
    DefaultValue="0" />
                </InsertParameters>
                <UpdateParameters>
                    <asp:Parameter Name="UserName" Type="String" />
                    <asp:Parameter Name="UserId" Type="Int32" DefaultValue="0" />
                </UpdateParameters>
                <DeleteParameters>
                    <asp:Parameter Name="UserId" Type="Int32" DefaultValue="0" />
                </DeleteParameters>
            </asp:SqlDataSource>
        </form>
    </body>
    </html>
                       
                        

    Posted by: Admin
    Posted on: 9/12/2009 at 2:19 PM
    Tags: , ,
    Categories: Asp.net
    Actions: E-mail | Kick it! | DZone it! | del.icio.us
    Post Information: Permalink | Comments (69) | Post RSSRSS comment feed

    ToolBox Data Control SqlDataSource

    SqlDataSource Web Server Control

    in ASP.NET environment,This article describes you how to work with SQLDataSource Web Control.The SqlDataSource can be working together with web controls such as Gridview,Repeater,Datalist and etc. The SqlDataSource control enables you to use a Web control to access data from a relational data base, including Microsoft SQL Server and Oracle databases, as well as OLE DB and ODBC data sources.

    This SqlDataSource can be interacting with ADO.NET Classes such as System.Data.SqlClient, System.Data.OleDb, System.Data.Odbc and System.Data.OracleClient.SqlDataSource helps us to to access and manipulate data in an ASP.NET page without using ADO.NET classes directly.

    Using the SqlDataSource Control to a Data Source

    While using the SqlDataSource, you must specify the ProviderName property to respect to the Database type when using other than System.Data.SqlClient because default provider is System.Data.SqlClient and provide the ConnectionString property which includes the server name, database (catalog) name, and information about how to authenticate the user when connecting to a SQL Server.

    The following code snippets represents the SqlDatasource to a Data Source.

    <html  >
      <head id="Head1" runat="server">
        <title>ASP.NET Example</title>
    </head>
    <body>
        <form id="form2" runat="server">
          <asp:SqlDataSource
              id="SqlDataSource1"
              runat="server"
              DataSourceMode="DataReader"
              ConnectionString="<%$ ConnectionStrings:Conn%>"
              SelectCommand="SELECT * FROM Table1">
          </asp:SqlDataSource>
    
          <asp:ListBox
              id="ListBox1"
              runat="server"
              DataTextField="UserName"
              DataSourceID="SqlDataSource1">
          </asp:ListBox>
    
        </form>
      </body>
    </html>
                      
     
    Data Commands of SqlDataSource

    The following Commands can be provided by the SqlDataSource ,

    • SelectCommand
    • UpdateCommand
    • DeleteCommand
    • InsertCommand

    you must render a SQL statement for the data source control to execute according the Command Property. If the data source control connects to a database that supports stored procedures, you can specify the name of a stored procedure in place of the SQL statement.and You can also supply a value to the Database at runtime as Parameter which can be denoted as,

    Select * From Table1 Where UserId = @User
                      
     
    DataSet or DataReader Objects using with SqlDataSource

    Using DataSet or DataReader Classes to receive the value of SqlDataSource control . You can specify which form to return by setting the data source control's DataSourceMode property. A DataSet object contains all the data in server memory, allowing you to manipulate the data in various ways after retrieving it. A data reader provides a read-only cursor that can fetch individual records.

    Logically, you use to return a dataset if you want to filter, sort, or page through data after retrieving it or if you want to maintain a cache. In contrast, you use a data reader when you simply want to return the data and are using a control on the page to display that data. For example, using a data reader is ideal for returning data that you want to display in a ListBox, DropDownList, or GridView control where a list of results is displayed in a read-only format.

    Caching with the SqlDataSource Control

    The primary goal of using the Caching concept to avoid too much of system memory to be used.The SqlDataSource control can cache data that it has retrieved, which can enhance the performance of your applications by avoiding expensive queries.

    To enable the caching Property,Simply set the EnableCaching is to true due to which is set to false initially.you can set the CacheDuration property to the number of seconds to cache data

    Filtering with the SqlDataSource Control

    If you have enabled caching for the SqlDataSource control and have specified a dataset as the format for data returned by a Select query, you can also filter the data without re-running the query. The SqlDataSource control supports a FilterExpression property that allows you to specify selection criteria that are applied to the data maintained by the data source control. You can also parameterize the filter expression by creating special FilterParameters objects that provide values at run time to the filter expression.

    To Connect a SQL Server Database via SqlDataSource
    • In Design view,from the Data group in the Toolbox, drag a SqlDataSource control onto the page.
    • On the SqlDataSource Tasks shortcut menu, click Configure Data Source - <datasourcename>. .
    • Click New Connection.
    • In the Add Connection dialog box, click Change.
    • In the Change Data Source dialog box, click Microsoft SQL Server, and then click OK.
    • In the Server name box, enter the name for your SQL Server database, and then under Logon to the server, enter the logon credentials.
    • In the Select or enter a database name list, enter a valid database on the server .
    • click Test connection.click ok
    • Select Yes, save this connection as, and enter a name for your connection for when it is stored in the application configuration file, and then click Next.
    • Select the database table, view, or stored procedure from which to retrieve results or specify your own SQL statement.
    • To test your query, click Next, and then click Test Query.
    • Click Finish.
    Selecting Data Using the SqlDataSource

    The following properties must be specified to retrieve data from a database using the SqlDataSource control,

    • ProviderName -Set to the name of the ADO.NET provider that represents the type of database.for ex,System.Data.SqlClient;
    • ConnectionString -Set to a connection string that works for your database.
    • SelectCommand -Set to an SQL query or stored procedure that returns data from the database.

    The following code snippets shows how you can set the ConnectionString and SelectCommand properties of a SqlDataSource for dispalying the data.

    <html  >
      <head id="Head1" runat="server">
        <title>ASP.NET Example</title>
    </head>
    <body>
        <form id="form2" runat="server">
          <asp:SqlDataSource
              id="SqlDataSource1"
              runat="server"
              DataSourceMode="DataReader"
              ConnectionString="<%$ ConnectionStrings:Conn%>"
              SelectCommand="SELECT * FROM Table1">
          </asp:SqlDataSource>
    
          <asp:ListBox
              id="ListBox1"
              runat="server"
              DataTextField="UserName"
              DataSourceID="SqlDataSource1">
          </asp:ListBox>
    
        </form>
      </body>
    </html>
                        
     
    Related Links

    Posted by: Admin
    Posted on: 9/11/2009 at 4:49 PM
    Tags: , ,
    Categories: Asp.net
    Actions: E-mail | Kick it! | DZone it! | del.icio.us
    Post Information: Permalink | Comments (86) | Post RSSRSS comment feed