Partilhar via


How to: Build and Run the Data-bound Web Parts Control Example

This topic contains instructions for building and running the data-bound WebPart control, for which a complete code example is provided in the topic Data-bound Web Parts Control Example. The code example demonstrates how to create a custom server control that binds a GridView control to a data source, but also inherits from the WebPart class so that it can participate in Web Parts applications. This topic gives the related information you will need to compile the code example and configure an ASP.NET Web application to run the control as a Web Parts control.

Compiling the WebPart Control

For the code example to run, you must compile this source code. You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. This code example uses dynamic compilation. For a walkthrough that demonstrates how to compile, see Walkthrough: Developing and Using a Custom Web Server Control.

To dynamically compile the data-bound WebPart control

  1. In the root folder of your Web application, create a folder named App_Code.

  2. Obtain the source code for the custom data-bound WebPart control from the topic Data-bound Web Parts Control Example. Place the source code file in the App_Code folder. The name of the file does not matter because you are using dynamic compilation, but the file must have the appropriate extension for the language you are using (such as .cs or .vb).

Using the Control in a Web Parts Application

Configuring an application to use Web Parts requires only that you have an ASP.NET Web site that can authenticate individual users, and a database enabled to handle application services including personalization. For this example (because it uses a data-bound control), you also need to create a connection string in the Web.config file that enables the data source to connect to the Northwind sample database. After the application is configured, in every Web Parts application you need to add a WebPartManager control and at least one WebPartZone control to each Web page that will host the WebPart and server controls in your Web Parts application. The second procedure below demonstrates how to add these controls, and to carry out the other steps needed to prepare the page to run the data-bound control.

To configure an ASP.NET application to run Web Parts controls

  1. Ensure that you have an ASP.NET Web application that is configured to recognize individual users. If you need directions on how to create such a site, see How to: Create and Configure Virtual Directories in IIS 5.0 and 6.0 or How to: Create and Configure Local ASP.NET Web Sites in IIS 6.0.

  2. Ensure that you have a configured personalization provider and database. Web Parts personalization is enabled by default, and it uses the SQL personalization provider (SqlPersonalizationProvider) with the Microsoft SQL Server Express (SSE) edition to store personalization data. This topic uses SSE and the default SQL provider. If you have SSE installed, no configuration is needed. SSE is available with Microsoft Visual Studio 2005 as an optional part of the installation, or as a free download from Microsoft.com. To use one of the full versions of Microsoft SQL Server, you must install and configure an ASP.NET application services database, and configure the SQL personalization provider to connect to that database. For details, see Creating and Configuring the Application Services Database for SQL Server. You can also create and configure a custom provider to use with other, non-SQL databases or storage solutions. For details and a code example, see Implementing a Membership Provider.

  3. Create a connection string so that the data-bound control can connect to the sample Northwind database. To run the example, you will need access to the sample Northwind database provided with SQL Server. If you do not have the Northwind sample database installed, you can download scripts to create and install the database from the Microsoft Download Center.

    A recommended approach for connection strings is to place them in the Web.config file for your application. For more information about configuration files, see ASP.NET Configuration Files. The following code example shows a connection string in the Web.config file, connecting to a local instance of Northwind running on SSE. Note that the single quotation marks (') that would normally delimit the path to the database file are rendered as entities ("). This is required because Web.config is an XML file.

    <connectionStrings>
      <add name="nwind" 
        connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=
        &quot;C:\SQL Server 2000 Sample Databases\NORTHWND.MDF&quot;;
        Initial Catalog=Northwind;Integrated Security=True;"
        providerName="System.Data.SqlClient" />
    </connectionStrings>
    

    Note

    It is recommended that you encrypt any sensitive information such as a password contained in a connection string. For details on encrypting configuration data, see Walkthrough: Encrypting Configuration Information Using Protected Configuration.

  4. In the <system.web> section of the Web.config file, add a <webparts> element. This is not required for every Web Parts application, but certain features of Web Parts applications must be configured in this section if you want to use them. The sample data-bound WebPart control is enabled for exporting a configuration file containing its state and property data. Because the export feature is disabled by default in Web Parts applications, you must enable it in the <webParts> section. Add an enabledExport attribute to the <webParts> element and set its value to true, as in the following code example.

    <webParts enableExport="true" />
    
  5. Save and close the Web.config file.

To prepare a Web page to host Web Parts controls

  1. Create a user control that will enable users to switch between the available Web Parts display modes on the Web page. This control and the next step are not required to run the data-bound Web Parts control, but this is a feature that is useful on many Web Parts pages. In an editor, paste the following code for the user control, and save the file in your Web application's root folder with the name Displaymodemenucs.ascx or Displaymodemenuvb.ascx (depending on which language you are using).

    <!-- This user control recognizes what display modes are possible 
    on a page, given the zones that are present, and enables users to 
    switch among the display modes. -->
    <%@ control language="vb" classname="DisplayModeMenuVB"%>
    
    <script runat="server">
    
    ' Use a field to reference the current WebPartManager.
    Dim _manager As WebPartManager
    
    
    Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) 
        AddHandler Page.InitComplete, AddressOf InitComplete
    
    End Sub 
    
    
    Sub InitComplete(ByVal sender As Object, ByVal e As System.EventArgs) 
        _manager = WebPartManager.GetCurrentWebPartManager(Page)
    
        Dim browseModeName As String = WebPartManager.BrowseDisplayMode.Name
    
        ' Fill the dropdown with the names of supported display modes.
        Dim mode As WebPartDisplayMode
        For Each mode In  _manager.SupportedDisplayModes
            Dim modeName As String = mode.Name
            ' Make sure a mode is enabled before adding it.
            If mode.IsEnabled(_manager) Then
                Dim item As New ListItem(modeName + " Mode", modeName)
                DisplayModeDropdown.Items.Add(item)
            End If
        Next mode
    
    End Sub 
    
    
    ' Change the page to the selected display mode.
    Sub DisplayModeDropdown_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) 
        Dim selectedMode As String = DisplayModeDropdown.SelectedValue
    
        Dim mode As WebPartDisplayMode = _manager.SupportedDisplayModes(selectedMode)
        If Not (mode Is Nothing) Then
            _manager.DisplayMode = mode
        End If
    
    End Sub 
    
    
    Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs) 
        DisplayModeDropdown.SelectedValue = _manager.DisplayMode.Name
    
    End Sub 
    
    </script>
    <div>
      <asp:DropDownList ID="DisplayModeDropdown" 
        runat="server"  
        AutoPostBack="true" 
        OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    </div>
    
    <!-- This user control recognizes what display modes are possible 
    on a page, given the zones that are present, and enables users to 
    switch among the display modes. -->
    <%@ control language="C#" classname="DisplayModeMenuCS"%>
    
    <script runat="server">
    
     // Use a field to reference the current WebPartManager.
      WebPartManager _manager;
    
      void Page_Init(object sender, EventArgs e)
      {
        Page.InitComplete += new EventHandler(InitComplete);
      }  
    
      void InitComplete(object sender, System.EventArgs e)
      {
        _manager = WebPartManager.GetCurrentWebPartManager(Page);
    
        String browseModeName = WebPartManager.BrowseDisplayMode.Name;
    
        // Fill the dropdown with the names of supported display modes.
        foreach (WebPartDisplayMode mode in _manager.SupportedDisplayModes)
        {
          String modeName = mode.Name;
          // Make sure a mode is enabled before adding it.
          if (mode.IsEnabled(_manager))
          {
            ListItem item = new ListItem(modeName + " Mode", modeName);
            DisplayModeDropdown.Items.Add(item);
          }
        }
    
      }
    
      // Change the page to the selected display mode.
      void DisplayModeDropdown_SelectedIndexChanged(object sender, 
        EventArgs e)
      {
        String selectedMode = DisplayModeDropdown.SelectedValue;
    
        WebPartDisplayMode mode = _manager.SupportedDisplayModes[selectedMode];
        if (mode != null)
          _manager.DisplayMode = mode;
    
      }
    
      void Page_PreRender(object sender, EventArgs e)
      {
        DisplayModeDropdown.SelectedValue = _manager.DisplayMode.Name;
      }
    
    </script>
    <div>
      <asp:DropDownList ID="DisplayModeDropdown" 
        runat="server"  
        AutoPostBack="true" 
        OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    </div>
    
  2. Create a new ASP.NET page to host the custom WebPart control and the other controls. Add a Register directive to the page, just below the Page directive, to register the user control you just created. The directive contents depend on which language you are using, and should look like the following example.

    [Visual Basic]

    <%@ register src="displaymodevb.ascx" tagname="displaymodevb" 
        tagprefix="uc1" %>
    

    [C#]

    <%@ register src="displaymodecs.ascx" tagname="displaymodecs" 
        tagprefix="uc1" %>
    
  3. Now add a Register directive for the custom WebPart control. Because this topic uses dynamic compilation, you do not need to add an Assembly attribute to the directive. Just below the previous directive in the file, add another Register directive, assign an arbitrary string to its tagprefix attribute, and assign the namespace of the custom control to the namespace attribute, again depending on the language you used, as in the following example.

    [Visual Basic]

    <%@ register tagprefix="aspSample" 
        namespace="Samples.AspNet.VB.Controls" %>
    
    <%@ register tagprefix="aspSample" 
        namespace="Samples.AspNet.CS.Controls" %>
    
  4. Add an <asp:webpartmanager> element to the page, just inside the <form> element, as shown in the following code example. A WebPartManager control is required on every page that uses Web Parts.

    <asp:webpartmanager id="WebPartManager1" runat="server">
    </asp:webpartmanager>
    
  5. Declare the user control for switching display modes, just after the <asp:webpartmanager> element. How you declare the control depends on which language you are using, as in the following code example.

    [Visual Basic]

    <uc1:displaymodevb id="Displaymodevb1" runat="server" />
    
    <uc1:displaymodecs id="Displaymodecs1" runat="server" />
    
  6. After the user control, add a table with one row and two columns, to structure the layout of the controls on the page. The table markup should look like the following code example.

    <table style="width: 80%; position: relative">
      <tr valign="top">
        <td style="width: 40%">
        </td>
        <td style="width: 40%">
        </td>
      </tr>
    </table>
    
  7. Within each set of <td> tags, add an <asp:webpartzone> element. A zone that derives from the WebPartZoneBase class is required to contain WebPart controls and enable them to have full Web Parts functionality. The markup for the first zone should look like the following code example.

    <asp:webpartzone id="WebPartZone1" runat="server" 
      style="position: relative" >
      <parttitlestyle font-size="14" font-names="Verdana" />
      <zonetemplate>
      </zonetemplate>
    </asp:webpartzone>
    

    The markup for the second zone should look like this.

    <asp:webpartzone id="WebPartZone2" runat="server" 
      style="position: relative" >
      <zonetemplate>
      </zonetemplate>
    </asp:webpartzone>
    
  8. Declare the custom data-bound WebPart control in the first zone, between the <zonetemplate> tags, as shown in the following code example. Note that the markup uses the tag prefix defined in the Register directive for the control, as well as the class name for the custom control. Also note that a custom property defined in the control--ConnectionString--appears as an attribute with the connection string from the Web.config file assigned to it. This approach enables page developers to determine what connection string to use for the control. The markup should look like this.

    <aspSample:SmallGridWebPart id="grid1" runat="server" 
      title="Customer Phone List" width="300" 
      connectionstring="<%$ ConnectionStrings:nwind %>"   />
    
  9. For comparison purposes, declare an ordinary calendar server control in the second zone, between the <zonetemplate> tags. Because you are placing the control in a WebPartZone control, it will behave like a WebPart control at run time. For details on using server controls in Web Parts applications, see Using ASP.NET Server Controls in Web Parts Applications. The markup should look like the following code example.

    <asp:calendar id="Calendar1" runat="server" 
      style="position: relative"></asp:calendar>
    
  10. Save and close the page. You are now ready to run the page and test the custom WebPart control. The completed code for the page should look like the following code example.

    <%@ Page Language="VB" %>
    <!-- Register the user control to change display modes. -->
    <%@ register src="displaymodevb.ascx" tagname="displaymodevb" 
        tagprefix="uc1" %>
    <!-- Register the namespace that contains the custom WebPart 
    control. Note there is no assembly attribute because this example 
    uses dynamic compilation, by placing the source file for the 
    control in an App_Code subfolder. -->
    <%@ register tagprefix="aspSample" 
        namespace="Samples.AspNet.VB.Controls" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
          <asp:webpartmanager id="WebPartManager1" runat="server">
          </asp:webpartmanager>
          <uc1:displaymodevb id="Displaymodevb1" runat="server" />
          <br />
          <table style="width: 80%; position: relative">
            <tr valign="top">
              <td style="width: 40%">
                <asp:webpartzone id="WebPartZone1" runat="server" 
                  style="position: relative" >
                  <parttitlestyle font-size="14" font-names="Verdana" />
                  <zonetemplate>
                    <aspSample:SmallGridWebPart id="grid1" runat="server" 
                      title="Customer Phone List" width="300" 
                      connectionstring="<%$ ConnectionStrings:nwind %>"  
                      />
                  </zonetemplate>
                </asp:webpartzone>
              </td>
              <td style="width: 40%">
                <asp:webpartzone id="WebPartZone2" runat="server" 
                  style="position: relative">
                  <zonetemplate>
                    <asp:calendar id="Calendar1" runat="server" 
                      style="position: relative"></asp:calendar>
                  </zonetemplate>
                </asp:webpartzone>
              </td>
            </tr>
          </table>
    
        </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" %>
    <!-- Register the user control to change display modes. -->
    <%@ register src="displaymodecs.ascx" tagname="displaymodecs" 
        tagprefix="uc1" %>
    <!-- Register the namespace that contains the custom WebPart 
    control. Note there is no assembly attribute because this example 
    uses dynamic compilation, by placing the source file for the 
    control in an App_Code subfolder. -->
    <%@ register tagprefix="aspSample" 
        namespace="Samples.AspNet.CS.Controls" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
          <asp:webpartmanager id="WebPartManager1" runat="server">
          </asp:webpartmanager>
          <uc1:displaymodecs id="Displaymodecs1" runat="server" />
          <br />
          <table style="width: 80%; position: relative">
            <tr valign="top">
              <td style="width: 40%">
                <asp:webpartzone id="WebPartZone1" runat="server" 
                  style="position: relative" >
                  <parttitlestyle font-size="14" font-names="Verdana, Arial" />
                  <zonetemplate>
                    <aspSample:SmallGridWebPart id="grid1" runat="server" 
                      title="Customer Phone List" width="300" 
                      connectionstring="<%$ ConnectionStrings:nwind %>"  
                      />
                  </zonetemplate>
                </asp:webpartzone>
              </td>
              <td style="width: 40%">
                <asp:webpartzone id="WebPartZone2" runat="server" 
                  style="position: relative">
                  <zonetemplate>
                    <asp:calendar id="Calendar1" runat="server" 
                      style="position: relative"></asp:calendar>
                  </zonetemplate>
                </asp:webpartzone>
              </td>
            </tr>
          </table>
    
        </div>
        </form>
    </body>
    </html>
    

See Also

Concepts

Creating a Data-bound Web Parts Control

Data-bound Web Parts Control Example