FormViewUpdateEventHandler Делегат
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Представляет метод, обрабатывающий событие ItemUpdating элемента управления FormView.
public delegate void FormViewUpdateEventHandler(System::Object ^ sender, FormViewUpdateEventArgs ^ e);
public delegate void FormViewUpdateEventHandler(object sender, FormViewUpdateEventArgs e);
type FormViewUpdateEventHandler = delegate of obj * FormViewUpdateEventArgs -> unit
Public Delegate Sub FormViewUpdateEventHandler(sender As Object, e As FormViewUpdateEventArgs)
Параметры
- sender
- Object
Источник события.
Объект FormViewUpdateEventArgs, содержащий данные события.
Примеры
В следующем примере показано, как программным способом FormViewUpdateEventHandler добавить делегат в ItemUpdating событие FormView элемента управления .
Важно!
В этом примере имеется текстовое поле, принимающее вводимые пользователем данные, что является потенциальной угрозой безопасности. По умолчанию данные, вводимые пользователем на веб-страницах ASP.NET, проверяются на наличие скриптов и HTML-элементов. Дополнительные сведения см. в разделе Общие сведения об использовании сценариев.
<%@ Page language="C#" %>
<%@ import namespace="System.Data"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
// To dynamically create a template for a FormView control,
// you must create a custom template class to represent
// the template. This template class represents the item
// template for a FormView control.
private sealed class EmployeeItemTemplate : ITemplate
{
// When implementing the ITemplate interface, you must
// implement the InstantiateIn method. The FormView
// control calls this method to create the template's
// content.
void ITemplate.InstantiateIn(Control container)
{
// Create the child controls contained in the template.
// For this example, the item template displays the
// FirstName and LastName fields from the data source.
// To support data binding, create event handlers
// for the DataBinding event of each child control.
// The event handlers must bind the appropriate value
// to each control.
Label firstNameLabel = new Label();
firstNameLabel.ID = "FirstNameLabel";
firstNameLabel.DataBinding += new EventHandler(FirstNameLabel_DataBinding);
LiteralControl nameLineBreak = new LiteralControl("<br/>");
LiteralControl buttonLineBreak = new LiteralControl("<br/>");
Label lastNameLabel = new Label();
lastNameLabel.ID = "LastNameLabel";
lastNameLabel.DataBinding += new EventHandler(LastNameLabel_DataBinding);
Button editButton = new Button();
editButton.ID = "EditButton";
editButton.CommandName = "Edit";
editButton.Text = "Edit";
// Add the controls to the Controls collection of the
// container control.
container.Controls.Add(firstNameLabel);
container.Controls.Add(nameLineBreak);
container.Controls.Add(lastNameLabel);
container.Controls.Add(buttonLineBreak);
container.Controls.Add(editButton);
}
// This event handler binds the value of the FirstName field
// to the FirstNameLabel Label control displayed in the template.
private void FirstNameLabel_DataBinding(Object sender, EventArgs e)
{
// Use the sender parameter to retrieve the Label control
// being bound to data.
Label firstNameLabelControl = (Label)sender;
// Retrieve the value to bind to the Label control. First,
// use the NamingContainer property to retrieve the parent
// control of the Label control. In this example, the parent
// control is the FormView control.
FormView formViewContainer = (FormView)firstNameLabelControl.NamingContainer;
// Get the data item bound to the FormView control.
DataRowView rowView = (DataRowView)formViewContainer.DataItem;
// Use the data item to retrieve the value of the FirstName field.
// Set the Text property of the Label control to this value.
firstNameLabelControl.Text = rowView["FirstName"].ToString();
}
// This event handler binds the value of the LastName field
// to the LastNameLabel Label control displayed in the template.
private void LastNameLabel_DataBinding(Object sender, EventArgs e)
{
// Use the sender parameter to retrieve the Label control
// being bound to data.
Label lastNameLabelControl = (Label)sender;
// Retrieve the value to bind to the Label control. First,
// use the NamingContainer property to retrieve the parent
// control of the Label control. In this example, the parent
// control is the FormView control.
FormView formViewContainer = (FormView)lastNameLabelControl.NamingContainer;
// Get the data item bound to the FormView control.
DataRowView rowView = (DataRowView)formViewContainer.DataItem;
// Use the data item to retrieve the value of the LastName field.
// Set the Text property of the Label control to this value.
lastNameLabelControl.Text = rowView["LastName"].ToString();
}
}
// This template class represents the edit item
// template for a FormView control.
private sealed class EmployeeEditItemTemplate : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
// Create the child controls contained in the template.
// The edit item template should contain the input
// controls for the user to edit a record.
TextBox firstNameTextBox = new TextBox();
firstNameTextBox.ID = "FirstNameTextBox";
LiteralControl nameLineBreak = new LiteralControl("<br/>");
LiteralControl buttonLineBreak = new LiteralControl("<br/>");
TextBox lastNameTextBox = new TextBox();
lastNameTextBox.ID = "LastNameTextBox";
Button updateButton = new Button();
updateButton.ID = "UpdateButton";
updateButton.CommandName = "Update";
updateButton.Text = "Update";
Button cancelButton = new Button();
cancelButton.ID = "CancelButton";
cancelButton.CommandName = "Cancel";
cancelButton.Text = "Cancel";
// Add the controls to the Controls collection of the
// container control.
container.Controls.Add(firstNameTextBox);
container.Controls.Add(nameLineBreak);
container.Controls.Add(lastNameTextBox);
container.Controls.Add(buttonLineBreak);
container.Controls.Add(updateButton);
container.Controls.Add(cancelButton);
}
}
void Page_Load(Object sender, EventArgs e)
{
// Create a new FormView object.
FormView employeesFormView = new FormView();
// Set the FormView object's properties.
employeesFormView.ID = "EmployeesFormView";
employeesFormView.DataSourceID = "EmployeeSource";
employeesFormView.AllowPaging = true;
employeesFormView.HeaderText = "Employee Name";
employeesFormView.DataKeyNames = new String[1] { "EmployeeID" };
// Programmatically register the event handlers for the
// FormView control.
employeesFormView.ItemUpdated += new FormViewUpdatedEventHandler(EmployeeFormView_ItemUpdated);
employeesFormView.ItemUpdating += new FormViewUpdateEventHandler(EmployeeFormView_ItemUpdating);
// Create the dynamic templates using the custom template classes.
employeesFormView.ItemTemplate = new EmployeeItemTemplate();
employeesFormView.EditItemTemplate = new EmployeeEditItemTemplate();
// Add the FormView object to the Controls collection
// of the PlaceHolder control.
FormViewPlaceHolder.Controls.Add(employeesFormView);
}
void EmployeeFormView_ItemUpdating(Object sender, FormViewUpdateEventArgs e)
{
// Because the FormView control is dynamically generated,
// the NewValues collection must be programmatically populated
// with the values for the record to update.
// Use the sender argument to retrieve the FormView
// control that raised the event.
FormView employeeFormView = (FormView)sender;
// Retrieve the data row from the FormView control.
FormViewRow row = employeeFormView.Row;
// Retrieve the TextBox controls that contain the updated values
// entered by the user.
TextBox firstNameTextBox = (TextBox)row.FindControl("FirstNameTextBox");
TextBox lastNameTextBox = (TextBox)row.FindControl("LastNameTextBox");
if (firstNameTextBox != null && lastNameTextBox != null)
{
// Add the new values to the NewValues collections.
e.NewValues.Add("FirstName", firstNameTextBox.Text);
e.NewValues.Add("LastName", lastNameTextBox.Text);
}
}
void EmployeeFormView_ItemUpdated(Object sender, FormViewUpdatedEventArgs e)
{
// Use the Exception property to determine whether an exception
// occurred during the update operation.
if (e.Exception == null)
{
// Use the AffectedRows property to determine whether the
// record was updated. Sometimes an error might occur that
// does not raise an exception, but prevents the update
// operation from completing.
if (e.AffectedRows == 1)
{
MessageLabel.Text = "Record updated successfully.";
}
else
{
MessageLabel.Text = "An error occurred during the update operation.";
// Use the KeepInUpdateMode property to keep the control in edit mode
// when an error occurs during the update operation.
e.KeepInEditMode = true;
}
}
else
{
// Insert the code to handle the exception.
MessageLabel.Text = e.Exception.Message;
// Use the ExceptionHandled property to indicate that the
// exception has already been handled.
e.ExceptionHandled = true;
e.KeepInEditMode = true;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>FormView Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>FormView Example</h3>
<!-- Use a PlaceHolder control as the container for the -->
<!-- dynamically generated FormView control. -->
<asp:placeholder id="FormViewPlaceHolder"
runat="server"/>
<br/><br/>
<asp:label id="MessageLabel"
forecolor="Red"
runat="server"/>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="EmployeeSource"
selectcommand="Select [EmployeeID], [LastName], [FirstName] From [Employees]"
updatecommand="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName Where [EmployeeID]=@EmployeeID"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server"/>
</form>
</body>
</html>
<%@ Page language="VB" %>
<%@ import namespace="System.Data"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
' To dynamically create a template for a FormView control,
' you must create a custom template class to represent
' the template. This template class represents the item
' template for a FormView control.
Private NotInheritable Class EmployeeItemTemplate
Implements ITemplate
' When implementing the ITemplate interface, you must
' implement the InstantiateIn method. The FormView
' control calls this method to create the template's
' content.
Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
' Create the child controls contained in the template.
' For this example, the item template displays the
' FirstName and LastName fields from the data source.
' To support data binding, create event handlers
' for the DataBinding event of each child control.
' The event handlers must bind the appropriate value
' to each control.
Dim firstNameLabel As New Label()
firstNameLabel.ID = "FirstNameLabel"
AddHandler firstNameLabel.DataBinding, AddressOf FirstNameLabel_DataBinding
Dim nameLineBreak As New LiteralControl("<br/>")
Dim buttonLineBreak As New LiteralControl("<br/>")
Dim lastNameLabel As New Label()
lastNameLabel.ID = "LastNameLabel"
AddHandler lastNameLabel.DataBinding, AddressOf LastNameLabel_DataBinding
Dim editButton As New Button()
editButton.ID = "EditButton"
editButton.CommandName = "Edit"
editButton.Text = "Edit"
' Add the controls to the Controls collection of the
' container control.
container.Controls.Add(firstNameLabel)
container.Controls.Add(nameLineBreak)
container.Controls.Add(lastNameLabel)
container.Controls.Add(buttonLineBreak)
container.Controls.Add(editButton)
End Sub
' This event handler binds the value of the FirstName field
' to the FirstNameLabel Label control displayed in the template.
Private Sub FirstNameLabel_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
' Use the sender parameter to retrieve the Label control
' being bound to data.
Dim firstNameLabelControl As Label = CType(sender, Label)
' Retrieve the value to bind to the Label control. First,
' use the NamingContainer property to retrieve the parent
' control of the Label control. In this example, the parent
' control is the FormView control.
Dim formViewContainer As FormView = CType(firstNameLabelControl.NamingContainer, FormView)
' Get the data item bound to the FormView control.
Dim rowView As DataRowView = CType(formViewContainer.DataItem, DataRowView)
' Use the data item to retrieve the value of the FirstName field.
' Set the Text property of the Label control to this value.
firstNameLabelControl.Text = rowView("FirstName").ToString()
End Sub
' This event handler binds the value of the LastName field
' to the LastNameLabel Label control displayed in the template.
Private Sub LastNameLabel_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
' Use the sender parameter to retrieve the Label control
' being bound to data.
Dim lastNameLabelControl As Label = CType(sender, Label)
' Retrieve the value to bind to the Label control. First,
' use the NamingContainer property to retrieve the parent
' control of the Label control. In this example, the parent
' control is the FormView control.
Dim formViewContainer As FormView = CType(lastNameLabelControl.NamingContainer, FormView)
' Get the data item bound to the FormView control.
Dim rowView As DataRowView = CType(formViewContainer.DataItem, DataRowView)
' Use the data item to retrieve the value of the LastName field.
' Set the Text property of the Label control to this value.
lastNameLabelControl.Text = rowView("LastName").ToString()
End Sub
End Class
' This template class represents the edit item
' template for a FormView control.
Private NotInheritable Class EmployeeEditItemTemplate
Implements ITemplate
Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
' Create the child controls contained in the template.
' The edit item template should contain the input
' controls for the user to edit a record.
Dim firstNameTextBox As New TextBox()
firstNameTextBox.ID = "FirstNameTextBox"
Dim nameLineBreak As New LiteralControl("<br/>")
Dim buttonLineBreak As New LiteralControl("<br/>")
Dim lastNameTextBox As New TextBox()
lastNameTextBox.ID = "LastNameTextBox"
Dim updateButton As New Button()
updateButton.ID = "UpdateButton"
updateButton.CommandName = "Update"
updateButton.Text = "Update"
Dim cancelButton As New Button()
cancelButton.ID = "CancelButton"
cancelButton.CommandName = "Cancel"
cancelButton.Text = "Cancel"
' Add the controls to the Controls collection of the
' container control.
container.Controls.Add(firstNameTextBox)
container.Controls.Add(nameLineBreak)
container.Controls.Add(lastNameTextBox)
container.Controls.Add(buttonLineBreak)
container.Controls.Add(updateButton)
container.Controls.Add(cancelButton)
End Sub
End Class
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Create a new FormView object.
Dim employeesFormView As New FormView()
' Set the FormView object's properties.
employeesFormView.ID = "EmployeesFormView"
employeesFormView.DataSourceID = "EmployeeSource"
employeesFormView.AllowPaging = True
employeesFormView.HeaderText = "Employee Name"
Dim keyArray() As String = {"EmployeeID"}
employeesFormView.DataKeyNames = keyArray
' Programmatically register the event handlers for the
' FormView control.
AddHandler employeesFormView.ItemUpdated, AddressOf EmployeeFormView_ItemUpdated
AddHandler employeesFormView.ItemUpdating, AddressOf EmployeeFormView_ItemUpdating
' Create the dynamic templates using the custom template classes.
employeesFormView.ItemTemplate = New EmployeeItemTemplate()
employeesFormView.EditItemTemplate = New EmployeeEditItemTemplate()
' Add the FormView object to the Controls collection
' of the PlaceHolder control.
FormViewPlaceHolder.Controls.Add(employeesFormView)
End Sub
Sub EmployeeFormView_ItemUpdating(ByVal sender As Object, ByVal e As FormViewUpdateEventArgs)
' Because the FormView control is dynamically generated,
' the NewValues collection must be programmatically populated
' with the values for the record to update.
' Use the sender argument to retrieve the FormView
' control that raised the event.
Dim employeeFormView As FormView = CType(sender, FormView)
' Retrieve the data row from the FormView control.
Dim row As FormViewRow = employeeFormView.Row
' Retrieve the TextBox controls that contain the updated values
' entered by the user.
Dim firstNameTextBox As TextBox = CType(row.FindControl("FirstNameTextBox"), TextBox)
Dim lastNameTextBox As TextBox = CType(row.FindControl("LastNameTextBox"), TextBox)
If firstNameTextBox IsNot Nothing And lastNameTextBox IsNot Nothing Then
' Add the new values to the NewValues collections.
e.NewValues.Add("FirstName", firstNameTextBox.Text)
e.NewValues.Add("LastName", lastNameTextBox.Text)
End If
End Sub
Sub EmployeeFormView_ItemUpdated(ByVal sender As Object, ByVal e As FormViewUpdatedEventArgs)
' Use the Exception property to determine whether an exception
' occurred during the update operation.
If e.Exception Is Nothing Then
' Use the AffectedRows property to determine whether the
' record was updated. Sometimes an error might occur that
' does not raise an exception, but prevents the update
' operation from completing.
If e.AffectedRows = 1 Then
MessageLabel.Text = "Record updated successfully."
Else
MessageLabel.Text = "An error occurred during the update operation."
' Use the KeepInUpdateMode property to keep the control in edit mode
' when an error occurs during the update operation.
e.KeepInEditMode = True
End If
Else
' Insert the code to handle the exception.
MessageLabel.Text = e.Exception.Message
' Use the ExceptionHandled property to indicate that the
' exception has already been handled.
e.ExceptionHandled = True
e.KeepInEditMode = True
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>FormView Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>FormView Example</h3>
<!-- Use a PlaceHolder control as the container for the -->
<!-- dynamically generated FormView control. -->
<asp:placeholder id="FormViewPlaceHolder"
runat="server"/>
<br/><br/>
<asp:label id="MessageLabel"
forecolor="Red"
runat="server"/>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="EmployeeSource"
selectcommand="Select [EmployeeID], [LastName], [FirstName] From [Employees]"
updatecommand="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName Where [EmployeeID]=@EmployeeID"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server"/>
</form>
</body>
</html>
В следующем примере показано, как декларативно добавить FormViewUpdateEventHandler делегат в ItemUpdating событие FormView элемента управления .
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void EmployeeFormView_ItemUpdating(Object sender, FormViewUpdateEventArgs e)
{
// Validate the field values entered by the user. This
// example determines whether the user left any fields
// empty. The names of the empty fields are added to
// an ArrayList object.
// Use the NewValues property to access the new
// values entered by the user.
ArrayList emptyFieldList = ValidateFields((OrderedDictionary)e.NewValues);
if (emptyFieldList.Count > 0)
{
// The user left some fields empty. Display an error message.
// Use the Keys property to retrieve the key field value.
String keyValue = e.Keys["EmployeeID"].ToString();
MessageLabel.Text = "You must enter a value for each field of record " +
keyValue + ".<br/>The following fields are missing:<br/><br/>";
// Display the missing fields.
foreach (String value in emptyFieldList)
{
// Use the OldValues property to access the original value
// of a field.
MessageLabel.Text += value + " - Original Value = " +
e.OldValues[value].ToString() + "<br />";
}
// Cancel the update operation.
e.Cancel = true;
}
else
{
// The field values passed validation. Clear the
// error message label.
MessageLabel.Text = "";
}
}
ArrayList ValidateFields(OrderedDictionary list)
{
// Create an ArrayList object to store the
// names of any empty fields.
ArrayList emptyFieldList = new ArrayList();
// Iterate though the field values entered by
// the user and check for an empty field.
foreach (DictionaryEntry entry in list)
{
if (entry.Value.Equals(""))
{
// Add the field name to the ArrayList object.
emptyFieldList.Add(entry.Key.ToString());
}
}
return emptyFieldList;
}
void EmployeeFormView_ModeChanged(Object sender, EventArgs e)
{
// Clear the error message label.
MessageLabel.Text = "";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>FormViewUpdateEventArgs Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>FormViewUpdateEventArgs Example</h3>
<asp:formview id="EmployeeFormView"
datasourceid="EmployeeSource"
allowpaging="true"
datakeynames="EmployeeID"
emptydatatext="No employees found."
onitemupdating="EmployeeFormView_ItemUpdating"
onmodechanged="EmployeeFormView_ModeChanged"
runat="server">
<itemtemplate>
<table>
<tr>
<td rowspan="6">
<asp:image id="EmployeeImage"
imageurl='<%# Eval("PhotoPath") %>'
alternatetext='<%# Eval("LastName") %>'
runat="server"/>
</td>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<b>Name:</b>
</td>
<td>
<%# Eval("FirstName") %> <%# Eval("LastName") %>
</td>
</tr>
<tr>
<td>
<b>Title:</b>
</td>
<td>
<%# Eval("Title") %>
</td>
</tr>
<tr style="height:150" valign="top">
<td>
<b>Address:</b>
</td>
<td>
<%# Eval("Address") %><br/>
<%# Eval("City") %> <%# Eval("Region") %>
<%# Eval("PostalCode") %><br/>
<%# Eval("Country") %>
</td>
</tr>
<tr>
<td colspan="2">
<asp:linkbutton id="Edit"
text="Edit"
commandname="Edit"
runat="server"/>
</td>
</tr>
</table>
</itemtemplate>
<edititemtemplate>
<table>
<tr>
<td rowspan="6">
<asp:image id="EmployeeEditImage"
imageurl='<%# Eval("PhotoPath") %>'
alternatetext='<%# Eval("LastName") %>'
runat="server"/>
</td>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<b><asp:Label runat="server"
AssociatedControlID="FirstNameUpdateTextBox"
Text="Name" />:</b>
</td>
<td>
<asp:textbox id="FirstNameUpdateTextBox"
text='<%# Bind("FirstName") %>'
accesskey="n" tabindex="1" runat="server"/>
<asp:textbox id="LastNameUpdateTextBox"
text='<%# Bind("LastName") %>'
accesskey="l" tabindex="2" runat="server"/>
</td>
</tr>
<tr>
<td>
<b><asp:Label runat="server"
AssociatedControlID="TitleUpdateTextBox"
Text="Title" />:</b>
</td>
<td>
<asp:textbox id="TitleUpdateTextBox"
text='<%# Bind("Title") %>'
accesskey="t" tabindex="3" runat="server"/>
</td>
</tr>
<tr>
<b><asp:Label runat="server"
AssociatedControlID="HireDateUpdateTextBox"
Text="Hire Date" />:</b>
<td>
<asp:textbox id="HireDateUpdateTextBox"
text='<%# Bind("HireDate", "{0:d}") %>'
accesskey="h" tabindex="4" runat="server" />
</td>
</tr>
<tr style="height:150" valign="top">
<td>
<b><asp:Label runat="server"
AssociatedControlID="AddressUpdateTextBox"
Text="Address" />:</b>
</td>
<td>
<asp:textbox id="AddressUpdateTextBox"
text='<%# Bind("Address") %>'
accesskey="a" tabindex="5" runat="server"/>
<br/>
<asp:textbox id="CityUpdateTextBox"
text='<%# Bind("City") %>'
accesskey="c" tabindex="6" runat="server"/>
<asp:textbox id="RegionUpdateTextBox"
text='<%# Bind("Region") %>'
width="40"
accesskey="r" tabindex="7" runat="server"/>
<asp:textbox id="PostalCodeUpdateTextBox"
text='<%# Bind("PostalCode") %>'
width="60"
accesskey="p" tabindex="8" runat="server"/>
<br/>
<asp:textbox id="CountryUpdateTextBox"
text='<%# Bind("Country") %>'
accesskey="u" tabindex="9" runat="server"/>
</td>
</tr>
<tr>
<td colspan="2">
<asp:linkbutton id="UpdateButton"
text="Update" tabindex="10"
commandname="Update"
runat="server"/>
<asp:linkbutton id="CancelButton"
text="Cancel" tabindex="11"
commandname="Cancel"
runat="server"/>
</td>
</tr>
</table>
</edititemtemplate>
</asp:formview>
<br/><br/>
<asp:label id="MessageLabel"
forecolor="Red"
runat="server"/>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="EmployeeSource"
selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [Address], [City], [Region], [PostalCode], [Country], [HireDate], [PhotoPath] From [Employees]"
updatecommand="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName, [Title]=@Title, [Address]=@Address, [City]=@City, [Region]=@Region, [PostalCode]=@PostalCode, [Country]=@Country Where [EmployeeID]=@EmployeeID"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server"/>
</form>
</body>
</html>
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub EmployeeFormView_ItemUpdating(ByVal sender As Object, ByVal e As FormViewUpdateEventArgs) Handles EmployeeFormView.ItemUpdating
' Validate the field values entered by the user. This
' example determines whether the user left any fields
' empty. The names of the empty fields are added to
' an ArrayList object.
' Use the NewValues property to access the new
' values entered by the user.
Dim emptyFieldList As ArrayList = ValidateFields(CType(e.NewValues, OrderedDictionary))
If emptyFieldList.Count > 0 Then
' The user left some fields empty. Display an error message.
' Use the Keys property to retrieve the key field value.
Dim keyValue As String = e.Keys("EmployeeID").ToString()
MessageLabel.Text = "You must enter a value for each field of record " & _
keyValue & ".<br/>The following fields are missing:<br/><br/>"
' Display the missing fields.
Dim value As String
For Each value In emptyFieldList
' Use the OldValues property access the original value
' of a field.
MessageLabel.Text &= value & " - Original Value = " & _
e.OldValues(value).ToString() & "<br />"
Next
' Cancel the update operation.
e.Cancel = True
Else
' The field values passed validation. Clear the
' error message label.
MessageLabel.Text = ""
End If
End Sub
Function ValidateFields(ByVal list As OrderedDictionary) As ArrayList
' Create an ArrayList object to store the
' names of any empty fields.
Dim emptyFieldList As New ArrayList()
' Iterate though the field values entered by
' the user and check for an empty field.
Dim entry As DictionaryEntry
For Each entry In list
If entry.Value.Equals("") Then
' Add the field name to the ArrayList object.
emptyFieldList.Add(entry.Key.ToString())
End If
Next
Return emptyFieldList
End Function
Sub EmployeeFormView_ModeChanged(ByVal sender As Object, ByVal e As EventArgs) Handles EmployeeFormView.ModeChanged
' Clear the error message label.
MessageLabel.Text = ""
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>FormViewUpdateEventArgs Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>FormViewUpdateEventArgs Example</h3>
<asp:formview id="EmployeeFormView"
datasourceid="EmployeeSource"
allowpaging="true"
datakeynames="EmployeeID"
emptydatatext="No employees found."
runat="server">
<itemtemplate>
<table>
<tr>
<td rowspan="6">
<asp:image id="EmployeeImage"
imageurl='<%# Eval("PhotoPath") %>'
alternatetext='<%# Eval("LastName") %>'
runat="server"/>
</td>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<b>Name:</b>
</td>
<td>
<%# Eval("FirstName") %> <%# Eval("LastName") %>
</td>
</tr>
<tr>
<td>
<b>Title:</b>
</td>
<td>
<%# Eval("Title") %>
</td>
</tr>
<tr style="height:150" valign="top">
<td>
<b>Address:</b>
</td>
<td>
<%# Eval("Address") %><br/>
<%# Eval("City") %> <%# Eval("Region") %>
<%# Eval("PostalCode") %><br/>
<%# Eval("Country") %>
</td>
</tr>
<tr>
<td colspan="2">
<asp:linkbutton id="Edit"
text="Edit"
commandname="Edit"
runat="server"/>
</td>
</tr>
</table>
</itemtemplate>
<edititemtemplate>
<table>
<tr>
<td rowspan="6">
<asp:image id="EmployeeEditImage"
imageurl='<%# Eval("PhotoPath") %>'
alternatetext='<%# Eval("LastName") %>'
runat="server"/>
</td>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<b><asp:Label runat="server"
AssociatedControlID="FirstNameUpdateTextBox"
Text="Name" />:</b>
</td>
<td>
<asp:textbox id="FirstNameUpdateTextBox"
text='<%# Bind("FirstName") %>'
accesskey="n" tabindex="1" runat="server"/>
<asp:textbox id="LastNameUpdateTextBox"
text='<%# Bind("LastName") %>'
accesskey="l" tabindex="2" runat="server"/>
</td>
</tr>
<tr>
<td>
<b><asp:Label runat="server"
AssociatedControlID="TitleUpdateTextBox"
Text="Title" />:</b>
</td>
<td>
<asp:textbox id="TitleUpdateTextBox"
text='<%# Bind("Title") %>'
accesskey="t" tabindex="3" runat="server"/>
</td>
</tr>
<tr>
<b><asp:Label runat="server"
AssociatedControlID="HireDateUpdateTextBox"
Text="Hire Date" />:</b>
<td>
<asp:textbox id="HireDateUpdateTextBox"
text='<%# Bind("HireDate", "{0:d}") %>'
accesskey="h" tabindex="4" runat="server" />
</td>
</tr>
<tr style="height:150" valign="top">
<td>
<b><asp:Label runat="server"
AssociatedControlID="AddressUpdateTextBox"
Text="Address" />:</b>
</td>
<td>
<asp:textbox id="AddressUpdateTextBox"
text='<%# Bind("Address") %>'
accesskey="a" tabindex="5" runat="server"/>
<br/>
<asp:textbox id="CityUpdateTextBox"
text='<%# Bind("City") %>'
accesskey="c" tabindex="6" runat="server"/>
<asp:textbox id="RegionUpdateTextBox"
text='<%# Bind("Region") %>'
width="40"
accesskey="r" tabindex="7" runat="server"/>
<asp:textbox id="PostalCodeUpdateTextBox"
text='<%# Bind("PostalCode") %>'
width="60"
accesskey="p" tabindex="8" runat="server"/>
<br/>
<asp:textbox id="CountryUpdateTextBox"
text='<%# Bind("Country") %>'
accesskey="u" tabindex="9" runat="server"/>
</td>
</tr>
<tr>
<td colspan="2">
<asp:linkbutton id="UpdateButton"
text="Update" tabindex="10"
commandname="Update"
runat="server"/>
<asp:linkbutton id="CancelButton"
text="Cancel" tabindex="11"
commandname="Cancel"
runat="server"/>
</td>
</tr>
</table>
</edititemtemplate>
</asp:formview>
<br/><br/>
<asp:label id="MessageLabel"
forecolor="Red"
runat="server"/>
<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="EmployeeSource"
selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [Address], [City], [Region], [PostalCode], [Country], [HireDate], [PhotoPath] From [Employees]"
updatecommand="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName, [Title]=@Title, [Address]=@Address, [City]=@City, [Region]=@Region, [PostalCode]=@PostalCode, [Country]=@Country Where [EmployeeID]=@EmployeeID"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server"/>
</form>
</body>
</html>
Комментарии
Элемент FormView управления вызывает ItemUpdating событие при нажатии кнопки "Обновить" (кнопки со свойством CommandName
"Обновить") в элементе управления, но до того, как FormView элемент управления обновит запись. Это позволяет предоставить метод обработки событий, который выполняет пользовательскую подпрограмму, например кодирование HTML или проверку значений записи перед ее обновлением в источнике данных при возникновении этого события.
При создании делегата FormViewUpdateEventHandler необходимо указать метод, обрабатывающий событие. Чтобы связать событие с обработчиком событий, нужно добавить в событие экземпляр делегата. Обработчик событий вызывается всякий раз, когда происходит событие, если делегат не удален. Дополнительные сведения о делегатах обработчика событий см. в разделе Обработка и вызов событий.
Методы расширения
GetMethodInfo(Delegate) |
Получает объект, представляющий метод, представленный указанным делегатом. |