Contains information about a single data-binding expression in an ASP.NET server control, which allows rapid-application development (RAD) designers, such as Microsoft Visual Studio, to create data-binding expressions at design time. This class cannot be inherited.
System.Web.UI.DataBinding
Namespace: System.Web.UI
Assembly: System.Web (in System.Web.dll)
Public NotInheritable Class DataBinding
public sealed class DataBinding
public ref class DataBinding sealed
[<Sealed>] type DataBinding = class end
The DataBinding type exposes the following members.
| Name | Description | |
|---|---|---|
|
DataBinding | Initializes a new instance of the DataBinding class. |
| Name | Description | |
|---|---|---|
|
Expression | Gets or sets the data-binding expression to be evaluated. |
|
PropertyName | Gets the name of the ASP.NET server control property to bind data to. |
|
PropertyType | Gets the .NET Framework type of the data-bound ASP.NET server control property. |
| Name | Description | |
|---|---|---|
|
Equals | Determines whether the specified object is the same instance of the DataBinding class as the current object. (Overrides Object.Equals(Object).) |
|
Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) |
|
GetHashCode | Retrieves the hash code for an instance of the DataBinding object. (Overrides Object.GetHashCode().) |
|
GetType | Gets the Type of the current instance. (Inherited from Object.) |
|
MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) |
|
ToString | Returns a string that represents the current object. (Inherited from Object.) |
Each data-binding expression in a server control is represented at design time by an instance of the DataBinding class. Any server control that contains one or more data-binding expressions has a DataBindingCollection object that contains the DataBinding objects. This collection is accessible through the Control class implementing the IDataBindingsAccessor interface. When you create a custom RAD designer, use that implementation to access the collection. Any DataBinding or DataBindingCollection objects associated with a server control exist only at design time. They do not exist at run time and, therefore, are not accessible during run time.
The following code example creates a DataBinding object and sets it equal to an existing object in the control's DataBindingCollection collection that has a propertyName parameter with a value of Text. If the collection contains a DataBinding object with a propertyName value of Text, this code returns the value of the object's Expression property. If there is no such object, it returns an empty string ("").
' Create the custom class that accesses the DataBinding and ' DataBindingCollection classes at design time. Public Class SimpleDesigner Inherits System.Web.UI.Design.ControlDesigner ' Create a Text property with accessors that obtain ' the property value from and set the property value ' to the Text key in the DataBindingCollection class. Public Property [Text]() As String Get Dim myBinding As DataBinding = DataBindings("Text") If Not (myBinding Is Nothing) Then Return myBinding.Expression End If Return String.Empty End Get Set(ByVal value As String) If value Is Nothing OrElse value.Length = 0 Then DataBindings.Remove("Text") Else Dim binding As DataBinding = DataBindings("Text") If binding Is Nothing Then binding = New DataBinding("Text", GetType(String), value) Else binding.Expression = value End If ' Call the DataBinding constructor, then add ' the initialized DataBinding object to the ' DataBindingCollection for this custom designer. Dim binding1 As DataBinding = CType(DataBindings.SyncRoot, DataBinding) DataBindings.Add(binding) DataBindings.Add(binding1) End If PropertyChanged("Text") End Set End Property Protected Sub PropertyChanged(ByVal propName As String) Dim myHtmlControlDesignBehavior As IControlDesignerTag = Me.Tag Dim myDataBindingCollection As DataBindingCollection Dim myDataBinding1, myDataBinding2 As DataBinding Dim myStringReplace1, myDataBindingExpression1, removedBinding, removedBindingAfterReplace, myDataBindingExpression2, myStringReplace2 As [String] Dim removedBindings1(), removedBindings2() As String Dim temp As Int32 If myHtmlControlDesignBehavior Is Nothing Then Return End If myDataBindingCollection = DataBindings ' Use the DataBindingCollection constructor to ' create the myDataBindingCollection1 object. ' Then set this object equal to the ' DataBindings property of the control created ' by this custom designer. Dim myDataBindingCollection1 As New DataBindingCollection() myDataBindingCollection1 = DataBindings myDataBindingCollection = DataBindings If (myDataBindingCollection.Contains(propName)) Then myDataBinding1 = myDataBindingCollection(propName) myStringReplace1 = propName.Replace(".", "-") If myDataBinding1 Is Nothing Then myHtmlControlDesignBehavior.RemoveAttribute(myStringReplace1) Return End If ' DataBinding is not null. myDataBindingExpression1 = [String].Concat("<%#", myDataBinding1.Expression, "%>") myHtmlControlDesignBehavior.SetAttribute(myStringReplace1, myDataBindingExpression1) Dim index As Integer = myStringReplace1.IndexOf("-") Else ' Use the DataBindingCollection.RemovedBindings ' property to set the value of the removedBindings ' arrays. removedBindings1 = DataBindings.RemovedBindings removedBindings2 = DataBindings.RemovedBindings temp = 0 While removedBindings2.Length > temp removedBinding = removedBindings2(temp) removedBindingAfterReplace = removedBinding.Replace("."c, "-"c) myHtmlControlDesignBehavior.RemoveAttribute(removedBindingAfterReplace) temp = temp & 1 End While End If ' Use the DataBindingCollection.GetEnumerator method ' to iterate through the myDataBindingCollection object ' and write the PropertyName, PropertyType, and Expression ' properties to a file for each DataBinding object ' in the MyDataBindingCollection object. myDataBindingCollection = DataBindings Dim myEnumerator As IEnumerator = myDataBindingCollection.GetEnumerator() While myEnumerator.MoveNext() myDataBinding2 = CType(myEnumerator.Current, DataBinding) Dim dataBindingOutput1, dataBindingOutput2, dataBindingOutput3 As [String] dataBindingOutput1 = [String].Concat("The property name is ", myDataBinding2.PropertyName) dataBindingOutput2 = [String].Concat("The property type is ", myDataBinding2.PropertyType.ToString(), "-", dataBindingOutput1) dataBindingOutput3 = [String].Concat("The expression is ", myDataBinding2.Expression, "-", dataBindingOutput2) WriteToFile(dataBindingOutput3) myDataBindingExpression2 = [String].Concat("<%#", myDataBinding2.Expression, "%>") myStringReplace2 = myDataBinding2.PropertyName.Replace(".", "-") myHtmlControlDesignBehavior.SetAttribute(myStringReplace2, myDataBindingExpression2) Dim index As Integer = myStringReplace2.IndexOf("-"c) End While ' while loop ends End Sub 'OnBindingsCollectionChanged Public Sub WriteToFile(ByVal input As String) ' The WriteToFile custom method writes ' the values of the DataBinding properties ' to a file on the C drive at design time. Dim myFile As StreamWriter = File.AppendText("C:\DataBindingOutput.txt") Dim encoder As New ASCIIEncoding() Dim ByteArray As Byte() = encoder.GetBytes(input) Dim CharArray As Char() = encoder.GetChars(ByteArray) myFile.WriteLine(CharArray, 0, input.Length) myFile.Close() End Sub 'WriteToFile End Class 'SimpleDesigner
// Create the custom class that accesses the DataBinding and // DataBindingCollection classes at design time. public class SimpleDesigner : System.Web.UI.Design.ControlDesigner { // Create a Text property with accessors that obtain // the property value from and set the property value // to the Text key in the DataBindingCollection class. public string Text { get { DataBinding myBinding = DataBindings["Text"]; if (myBinding != null) { return myBinding.Expression; } return String.Empty; } set { if ((value == null) || (value.Length == 0)) { DataBindings.Remove("Text"); } else { DataBinding binding = DataBindings["Text"]; if (binding == null) { binding = new DataBinding("Text", typeof(string), value); } else { binding.Expression = value; } // Call the DataBinding constructor, then add // the initialized DataBinding object to the // DataBindingCollection for this custom designer. DataBinding binding1 = (DataBinding)DataBindings.SyncRoot; DataBindings.Add(binding); DataBindings.Add(binding1); } PropertyChanged("Text"); } } protected void PropertyChanged(string propName) { IControlDesignerTag myHtmlControlDesignBehavior = this.Tag; DataBindingCollection myDataBindingCollection; DataBinding myDataBinding1, myDataBinding2; String myStringReplace1, myDataBindingExpression1, removedBinding, removedBindingAfterReplace, myDataBindingExpression2, myStringReplace2; string[] removedBindings1, removedBindings2; Int32 temp; if (myHtmlControlDesignBehavior == null) return; // Use the DataBindingCollection constructor to // create the myDataBindingCollection1 object. // Then set this object equal to the // DataBindings property of the control created // by this custom designer. DataBindingCollection myDataBindingCollection1 = new DataBindingCollection(); myDataBindingCollection1 = myDataBindingCollection = DataBindings; if (myDataBindingCollection.Contains(propName)) { myDataBinding1 = myDataBindingCollection[propName]; myStringReplace1 = propName.Replace(".", "-"); if (myDataBinding1 == null) { myHtmlControlDesignBehavior.RemoveAttribute(myStringReplace1); return; } // DataBinding is not null. myDataBindingExpression1 = String.Concat("<%#", myDataBinding1.Expression, "%>"); myHtmlControlDesignBehavior.SetAttribute(myStringReplace1, myDataBindingExpression1); int index = myStringReplace1.IndexOf("-"); } else { // Use the DataBindingCollection.RemovedBindings // property to set the value of the removedBindings // arrays. removedBindings2 = removedBindings1 = DataBindings.RemovedBindings; temp = 0; while (removedBindings2.Length > temp) { removedBinding = removedBindings2[temp]; removedBindingAfterReplace = removedBinding.Replace('.', '-'); myHtmlControlDesignBehavior.RemoveAttribute(removedBindingAfterReplace); temp = temp + 1; } } // Use the DataBindingCollection.GetEnumerator method // to iterate through the myDataBindingCollection object // and write the PropertyName, PropertyType, and Expression // properties to a file for each DataBinding object // in the MyDataBindingCollection object. myDataBindingCollection = DataBindings; IEnumerator myEnumerator = myDataBindingCollection.GetEnumerator(); while (myEnumerator.MoveNext()) { myDataBinding2 = (DataBinding)myEnumerator.Current; String dataBindingOutput1, dataBindingOutput2, dataBindingOutput3; dataBindingOutput1 = String.Concat("The property name is ", myDataBinding2.PropertyName); dataBindingOutput2 = String.Concat("The property type is ", myDataBinding2.PropertyType.ToString(), "-", dataBindingOutput1); dataBindingOutput3 = String.Concat("The expression is ", myDataBinding2.Expression, "-", dataBindingOutput2); WriteToFile(dataBindingOutput3); myDataBindingExpression2 = String.Concat("<%#", myDataBinding2.Expression, "%>"); myStringReplace2 = myDataBinding2.PropertyName.Replace(".", "-"); myHtmlControlDesignBehavior.SetAttribute(myStringReplace2, myDataBindingExpression2); int index = myStringReplace2.IndexOf('-'); }// while loop ends } public void WriteToFile(string input) { // The WriteToFile custom method writes // the values of the DataBinding properties // to a file on the C drive at design time. StreamWriter myFile = File.AppendText("C:\\DataBindingOutput.txt"); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] ByteArray = encoder.GetBytes(input); char[] CharArray = encoder.GetChars(ByteArray); myFile.WriteLine(CharArray, 0, input.Length); myFile.Close(); } }
.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Reference
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WT3AdvDatabinding.Web._Default" %><%@ Register Src="~/wuc/wucGenreSelector.ascx" TagName="GenreSelector" TagPrefix="uc" %>
<%@ Register Src="~/wuc/wucMovieEdit.ascx" TagName="MovieEdit" TagPrefix="uc" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc:GenreSelector ID="genreSelector" runat="server" AutoPostBack="True" />
<asp:ListView ID="lvwMovies" runat="server" DataSourceID="ObjectDataSource1" InsertItemPosition="LastItem" Datakeynames = "Id">
<LayoutTemplate>
<div><asp:PlaceHolder ID="ItemPlaceHolder" runat="server" /> </div>
</LayoutTemplate>
<ItemTemplate>
<div>
<asp:LinkButton ID="LinkButton" runat="server" CommandName="select"><%# Eval("Title")%> (<%# Eval("Year")%>)</asp:LinkButton>
</div>
</ItemTemplate>
<SelectedItemTemplate>
<div>
<h3><%# Eval("Title")%> (<%# Eval("Year")%>)</h3>
<p>Genre: <%# GetGenreName(Eval("Genre"))%></p>
<p><%# Eval("Plot")%></p>
<asp:Button ID="Button1" runat="server" Text="Edit" commandName="edit"/>
<asp:Button ID="Button2" runat="server" Text="Delete" CommandName="delete" />
</div>
</SelectedItemTemplate>
<InsertItemTemplate>
<br /><uc:MovieEdit ID="movieInsert" runat="server" Title='<%#Bind("Title")%>' Year='<%#Bind("Year")%>' Plot='<%#Bind("Plot") %>' Genre='<%#Bind("Genre") %>'/>
<asp:Button ID="btnInsert" runat="server" Text="Insert" CommandName="insert" ValidationGroup="movie-edit" />
</InsertItemTemplate>
<EditItemTemplate>
<uc:MovieEdit ID="movieEdit" runat="server" Title='<%#Bind("Title")%>' Year='<%#Bind("Year")%>' Plot='<%#Bind("Plot") %>' Genre='<%#Bind("Genre") %>'/>
<asp:Button ID="btnSave" runat="server" Text="Save" CommandName="update" ValidationGroup="movie-edit"/>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CommandName="cancel"/>
</EditItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="GetMovies" TypeName="WT3AdvDatabinding.BL.Movie"
DataObjectTypeName="WT3AdvDatabinding.BL.Movie" InsertMethod="InsertMovie"
DeleteMethod="DeleteMovie" UpdateMethod="UpdateMovie">
<SelectParameters>
<asp:ControlParameter ControlID="GenreSelector" Name="genre"
PropertyName="GenreId" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
</div>
</form>
</body>
</html>
Imports System.Configuration
Imports System.Data.Common
Public Class Genre
Private _id As String
Public Property Id() As String
Get
Return _id
End Get
Set(ByVal value As String)
_id = value
End Set
End Property
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private Shared _genres As List(Of Genre)
Public Shared Function GetGenre(ByVal id As String) As Genre
If _genres Is Nothing Then
_genres = Genre.GetGenres()
End If
Return _genres.Find(Function(g) g.Id = id)
End Function
Public Shared Function GetGenres() As List(Of Genre)
Dim reader As DbDataReader = GetReader("SELECT * FROM [Genre]")
Dim list As New List(Of Genre)
While reader.Read()
list.Add(FillGenre(reader))
End While
Return list
End Function
Private Shared Function FillGenre(ByVal reader As DbDataReader) As Genre
Dim g As New Genre
g.Id = reader("Id")
g.Name = reader("Name")
Return g
End Function
Private Shared Function GetConnection() As SqlConnection
Dim settings As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("movies2")
Dim con As New SqlConnection(settings.ConnectionString)
con.Open()
Return con
End Function
Private Shared Function GetCommand(ByVal sql As String, ByVal ParamArray parameters() As SqlParameter) As SqlCommand
Dim cmd As SqlCommand = GetConnection().CreateCommand()
cmd.CommandText = sql
cmd.Parameters.AddRange(parameters)
Return cmd
End Function
Private Shared Function GetReader(ByVal sql As String, ByVal ParamArray parameters() As SqlParameter) As SqlDataReader
Dim cmd As SqlCommand = GetCommand(sql, parameters)
Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
End Function
End Class
Imports System.Configuration
Imports System.Data.Common
Public Class Movie
Private _id As Integer
Public Property Id() As Integer
Get
Return _id
End Get
Set(ByVal value As Integer)
_id = value
End Set
End Property
Private _title As String
Public Property Title() As String
Get
Return _title
End Get
Set(ByVal value As String)
_title = value
End Set
End Property
Private _year As String
Public Property Year() As String
Get
Return _year
End Get
Set(ByVal value As String)
_year = value
End Set
End Property
Private _plot As String
Public Property Plot() As String
Get
Return _plot
End Get
Set(ByVal value As String)
_plot = value
End Set
End Property
Private _genre As String
Public Property Genre() As String
Get
Return _genre
End Get
Set(ByVal value As String)
_genre = value
End Set
End Property
Public Shared Function GetMovie(ByVal id As Integer) As Movie
Dim idPar As DbParameter = New SqlParameter()
idPar.ParameterName = "@Id"
idPar.Value = id
Dim reader As DbDataReader = GetReader("SELECT * FROM [Movie] WHERE [Id] = @Id", idPar)
If reader.Read() Then
Return FillMovie(reader)
End If
Return Nothing
End Function
Public Shared Function GetMovies(ByVal genre As String)
Dim genrePar As DbParameter = New SqlParameter()
genrePar.ParameterName = "@Genre"
genrePar.Value = genre
Dim reader As DbDataReader = GetReader("SELECT * FROM [Movie] WHERE [Genre] = @Genre", genrePar)
Dim list As New List(Of Movie)
While reader.Read()
list.Add(FillMovie(reader))
End While
Return list
End Function
Private Shared Function FillMovie(ByVal reader As DbDataReader) As Movie
Dim m As New Movie
m.Id = reader("Id")
m.Title = reader("Title")
m.Year = reader("Year")
m.Plot = reader("Plot")
m.Genre = reader("Genre")
Return m
End Function
Public Shared Sub InsertMovie(ByVal movie As Movie)
Execute("INSERT INTO [Movie]([Title], [Year], [Plot], [Genre]) VALUES (@Title, @Year, @Plot, @Genre)", _
New SqlParameter("@Title", movie.Title), _
New SqlParameter("@Year", movie.Year), _
New SqlParameter("@Plot", movie.Plot), _
New SqlParameter("@Genre", movie.Genre))
End Sub
Public Shared Sub UpdateMovie(ByVal movie As Movie)
Execute("UPDATE [Movie] SET [Title] = @Title, [Year] = @Year, [Plot] = @Plot, [Genre] = @Genre WHERE [Id] = @Id", _
New SqlParameter("@Title", movie.Title), _
New SqlParameter("@Year", movie.Year), _
New SqlParameter("@Plot", movie.Plot), _
New SqlParameter("@Genre", movie.Genre), _
New SqlParameter("@Id", movie.Id))
End Sub
Public Shared Sub DeleteMovie(ByVal movie As Movie)
Execute("DELETE FROM [Movie] WHERE [Id] = @Id", New SqlParameter("@Id", movie.Id))
End Sub
Private Shared Function GetConnection() As SqlConnection
Dim settings As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("movies2")
Dim con As New SqlConnection(settings.ConnectionString)
con.Open()
Return con
End Function
Private Shared Function GetCommand(ByVal sql As String, ByVal ParamArray parameters() As SqlParameter) As SqlCommand
Dim cmd As SqlCommand = GetConnection().CreateCommand()
cmd.CommandText = sql
cmd.Parameters.AddRange(parameters)
Return cmd
End Function
Private Shared Sub Execute(ByVal sql As String, ByVal ParamArray parameters() As SqlParameter)
Dim cmd As SqlCommand = GetCommand(sql, parameters)
cmd.ExecuteNonQuery()
cmd.Connection.Close()
End Sub
Private Shared Function GetReader(ByVal sql As String, ByVal ParamArray parameters() As SqlParameter) As SqlDataReader
Dim cmd As SqlCommand = GetCommand(sql, parameters)
Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
End Function
End Class