Data-bound Web Parts Control Example

The following code example shows how to create a custom data-bound control that inherits from the WebPart class and can be used in Web Parts applications. For details about how to build this control and use it in an ASP.NET application, see How to: Build and Run the Data-bound Web Parts Control Example.

Example

Code

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.Configuration
Imports System.Data.Sql
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  PublicClass SmallGridWebPart
    Inherits WebPart
    Private connString AsString
    ' Use predefined strings for commands in the data source.PrivateConst selectStmt AsString = "Select * from [Customers]"PrivateConst deleteCmd AsString = "DELETE FROM [Customers] " _
      & "WHERE [CustomerID] = @CustomerID"PrivateConst insertCmd AsString = "INSERT INTO [Customers] " _
      & "([CustomerID], [CompanyName], [ContactName], [Phone]) " _
      & "VALUES (@CustomerID, @CompanyName, @ContactName, @Phone)"PrivateConst updateCmd AsString = "UPDATE [Customers] SET " _
      & "[CompanyName] = @CompanyName, [ContactName] = @ContactName, " _
      & "[Phone] = @Phone WHERE [CustomerID] = @CustomerID"PublicSubNew()
      ExportMode = WebPartExportMode.All
    EndSub 'New
    ' This override prevents users from closing the control.PublicOverridesProperty AllowClose() AsBooleanGetReturnFalseEndGetSet(ByVal value AsBoolean)
        ' No implementation for the set accessor. We have to have         ' it because the base property has it, but we want to         ' prevent users from closing the control and developers         ' from being able to update the property.EndSetEndProperty
    ' Allow page developers to set the connection string.PublicProperty ConnectionString() AsStringGetReturn connString
      EndGetSet(ByVal value AsString)
        connString = value
      EndSetEndPropertyProtectedOverridesSub CreateChildControls()
      Controls.Clear()

      ' Create the SqlDataSource control.Dim ds AsNew SqlDataSource(Me.ConnectionString, selectStmt)
      ds.ID = "dsCustomers"
      ds.DataSourceMode = SqlDataSourceMode.DataSet
      ds.InsertCommandType = SqlDataSourceCommandType.Text
      ds.InsertCommand = insertCmd
      ds.UpdateCommandType = SqlDataSourceCommandType.Text
      ds.UpdateCommand = updateCmd
      ds.DeleteCommandType = SqlDataSourceCommandType.Text
      ds.DeleteCommand = deleteCmd
      Dim deleteParams AsNew ParameterCollection()
      deleteParams.Add(BuildParam("CustomerID", TypeCode.String))
      Dim insertParams AsNew ParameterCollection()
      insertParams.Add(BuildParam("CustomerID", TypeCode.String)) 
      insertParams.Add(BuildParam("CompanyName", TypeCode.String))
      insertParams.Add(BuildParam("ContactName", TypeCode.String)) 
      insertParams.Add(BuildParam("Phone", TypeCode.String))
      Dim updateParams AsNew ParameterCollection()
      updateParams.Add(BuildParam("CustomerID", TypeCode.String))
      updateParams.Add(BuildParam("CompanyName", TypeCode.String))
      updateParams.Add(BuildParam("ContactName", TypeCode.String))
      updateParams.Add(BuildParam("Phone", TypeCode.String))

      Me.Controls.Add(ds)

      ' Create the GridView control and bind it to the SqlDataSource.Dim grid AsNew GridView()
      grid.ID = "customerGrid"
      grid.Font.Size = 8
      grid.AllowPaging = True
      grid.AllowSorting = True
      grid.AutoGenerateColumns = FalseDim fields AsString() = {"CustomerID"}
      grid.DataKeyNames = fields
      grid.DataSourceID = "dsCustomers"Dim controlButton AsNew CommandField()
      controlButton.ShowEditButton = True
      controlButton.ShowSelectButton = True
      grid.Columns.Add(controlButton)
      Dim customerID As BoundField = BuildBoundField("CustomerID")
      customerID.ReadOnly = True
      grid.Columns.Add(customerID)
      grid.Columns.Add(BuildBoundField("CompanyName"))
      grid.Columns.Add(BuildBoundField("ContactName"))
      grid.Columns.Add(BuildBoundField("Phone"))

      Me.Controls.Add(grid)

    EndSub 'CreateChildControls


    PrivateFunction BuildParam(ByVal paramName AsString, _
      ByVal dataTypeCode As TypeCode) As Parameter

      Dim theParm AsNew Parameter(paramName, dataTypeCode)
      Return theParm

    EndFunction 'BuildParam


    PrivateFunction BuildBoundField(ByVal fieldName _
      AsString) As BoundField

      Dim theField AsNew BoundField()
      theField.DataField = fieldName
      theField.HeaderText = fieldName
      theField.SortExpression = fieldName
      Return theField

    EndFunction 'BuildBoundField
  EndClass 'SmallGridWebPart 

EndNamespace
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Web;
using System.Web.Configuration;
using System.Data.Sql;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Samples.AspNet.CS.Controls
{
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  publicclass SmallGridWebPart : WebPart
  {
    private String connString;

    // Use predefined strings for commands in the data source.privateconststring selectStmt = @"Select * from [Customers]";
    privateconststring deleteCmd = @"DELETE FROM [Customers] " +
      @"WHERE [CustomerID] = @CustomerID";
    privateconststring insertCmd = @"INSERT INTO [Customers] " +
      @"([CustomerID], [CompanyName], [ContactName], " +
      @"[Phone]) VALUES (@CustomerID, @CompanyName, " +
      @"@ContactName, @Phone)";
    privateconststring updateCmd = @"UPDATE [Customers] SET " +
      @"[CompanyName] = @CompanyName, [ContactName] = @ContactName, " +
      @"[Phone] = @Phone WHERE [CustomerID] = @CustomerID";


    public SmallGridWebPart()
    {
       ExportMode = WebPartExportMode.All;
    }

    // This override prevents users from closing the control.publicoverridebool AllowClose
    {
      get
      {
        returnfalse;
      }
      // No implementation for the set accessor. We have to have // it because the base property has it, but we want to // prevent users from closing the control and developers // from being able to update the property.set { ; }
    }

    // Allow page developers to set the connection string.public String ConnectionString
    {
      get { return connString; }
      set { connString = value; }
    }

    protectedoverridevoid CreateChildControls()
    {
      Controls.Clear();

      // Create the SqlDataSource control.
      SqlDataSource ds = new SqlDataSource(this.ConnectionString, selectStmt);
      ds.ID = "dsCustomers";
      ds.DataSourceMode = SqlDataSourceMode.DataSet;
      ds.InsertCommandType = SqlDataSourceCommandType.Text;
      ds.InsertCommand = insertCmd;
      ds.UpdateCommandType = SqlDataSourceCommandType.Text;
      ds.UpdateCommand = updateCmd;
      ds.DeleteCommandType = SqlDataSourceCommandType.Text;
      ds.DeleteCommand = deleteCmd;
      ParameterCollection deleteParams = new ParameterCollection();
      deleteParams.Add(BuildParam("CustomerID", TypeCode.String));
      ParameterCollection insertParams = new ParameterCollection();
      insertParams.Add(BuildParam("CustomerID", TypeCode.String));
      insertParams.Add(BuildParam("CompanyName", TypeCode.String));
      insertParams.Add(BuildParam("ContactName", TypeCode.String));
      insertParams.Add(BuildParam("Phone", TypeCode.String));
      ParameterCollection updateParams = new ParameterCollection();
      updateParams.Add(BuildParam("CustomerID", TypeCode.String));
      updateParams.Add(BuildParam("CompanyName", TypeCode.String));
      updateParams.Add(BuildParam("ContactName", TypeCode.String));
      updateParams.Add(BuildParam("Phone", TypeCode.String));

      this.Controls.Add(ds);

      // Create the GridView control and bind it to the SqlDataSource.
      GridView grid = new GridView();
      grid.ID = "customerGrid";
      grid.Font.Size = 8;
      grid.AllowPaging = true;
      grid.AllowSorting = true;
      grid.AutoGenerateColumns = false;
      String[] fields = { "CustomerID" };
      grid.DataKeyNames = fields;
      grid.DataSourceID = "dsCustomers";
      CommandField controlButton = new CommandField();
      controlButton.ShowEditButton = true;
      controlButton.ShowSelectButton = true;
      grid.Columns.Add(controlButton);
      BoundField customerID = BuildBoundField("CustomerID");
      customerID.ReadOnly = true;
      grid.Columns.Add(customerID);
      grid.Columns.Add(BuildBoundField("CompanyName"));
      grid.Columns.Add(BuildBoundField("ContactName"));
      grid.Columns.Add(BuildBoundField("Phone"));

      this.Controls.Add(grid);

    }

    private Parameter BuildParam(String paramName, TypeCode dataTypeCode)
    {
      Parameter theParm = new Parameter(paramName, dataTypeCode);
      return theParm;
    }

    private BoundField BuildBoundField(String fieldName)
    {
      BoundField theField = new BoundField();
      theField.DataField = fieldName;
      theField.HeaderText = fieldName;
      theField.SortExpression = fieldName;
      return theField;
    }

  } 

}

See Also

Tasks

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

Concepts

Creating a Data-bound Web Parts Control

Reference

WebPart

Other Resources

ASP.NET Web Parts Controls