ObjectDataSource.UpdateMethod Property
Assembly: System.Web (in system.web.dll)
/** @property */ public String get_UpdateMethod () /** @property */ public void set_UpdateMethod (String value)
public function get UpdateMethod () : String public function set UpdateMethod (value : String)
Not applicable.
Property Value
A string that represents the name of the method or function that the ObjectDataSource uses to update data. The default is an empty string.The ObjectDataSource control assumes that the method that is identified by the UpdateMethod property performs updates one at a time, rather than in a batch.
Note: |
|---|
| If you are not familiar with the Data Access features in ASP.NET 2.0, you should read some of these topics before continuing: |
The UpdateMethod property delegates to the UpdateMethod property of the ObjectDataSourceView object that is associated with the ObjectDataSource control.
Object Lifetime
The method that is identified by the UpdateMethod property can be an instance method or a static (Shared in Visual Basic) method. If it is an instance method, the business object is created and destroyed each time the method that is specified by the UpdateMethod property is called. You can handle the ObjectCreated and ObjectCreating events to work with the business object before the method that is specified by the UpdateMethod property is called. You can also handle the ObjectDisposing event that is raised after the method that is specified by the UpdateMethod property is called. If the business object implements the IDisposable interface, the Dispose method is called before the object is destroyed. If the method is static (Shared in Visual Basic), the business object is never created and you cannot handle the ObjectCreated, ObjectCreating, and ObjectDisposing events.
Parameter Merging
Parameters are added to the DeleteParameters collection from three sources:
-
From the data-bound control, at run time.
-
From the UpdateParameters element, declaratively.
-
From the Updating event handler, programmatically.
First, any parameters that are generated from data-bound controls are added to the UpdateParameters collection. For example, if the ObjectDataSource control is bound to a GridView control that has the columns Name and Number, the parameters for Name and Number are added to the collection. The exact name of the parameter depends on the OldValuesParameterFormatString property. The data type of these parameters is string. Next, the parameters that are listed in the UpdateParameters element are added. If a parameter in the UpdateParameters element is found with the same name as a parameter that is already in the UpdateParameters collection, the existing parameter is modified to match the parameter that is specified in the UpdateParameters element. Typically, this is used to modify the type of the data in the parameter. Finally, you can programmatically add and remove parameters in the Updating event, which occurs before the Update method is run. The method is resolved after the parameters are merged. Method resolution is discussed in the next section.
Security Note: |
|---|
| You should validate any parameter value that you receive from the client. The runtime simply substitutes the parameter value into the UpdateMethod property. |
Method Resolution
When the Update method is called, the data fields from the data-bound control, the parameters that were created declaratively in the UpdateParameters element, and the parameters that were added in the Updating event handler are all merged. (For more information, see the preceding section.) The ObjectDataSource control then attempts to find a method to call. First, it looks for one or more methods with the name that is specified in the UpdateMethod property. If no match is found, an InvalidOperationException exception is thrown. If a match is found, it then looks for matching parameter names. For example, suppose a type that is specified by the TypeName property has two methods named UpdateARecord. One UpdateARecord has one parameter, ID, and the other UpdateARecord has two parameters, Name and Number. If the UpdateParameters collection has only one parameter named ID, the UpdateARecord method with just the ID parameter is called. The type of the parameter is not checked in resolving the methods. The order of the parameters does not matter.
If the DataObjectTypeName property is set, the method is resolved in a different way. The ObjectDataSource looks for a method with the name that is specified in the UpdateMethod property that takes one parameter of the type that is specified in the DataObjectTypeName property. In this case, the name of the parameter does not matter.
This section contains two code examples. The first code example demonstrates how to use a DropDownList control, TextBox controls, and several ObjectDataSource objects to update data. The second code example shows the EmployeeLogic class that is used in the first code example.
The following code example demonstrates how to use a DropDownList control, TextBox controls, and several ObjectDataSource controls to update data. The DropDownList displays the name of a Northwind employee, while the TextBox controls are used to enter and update address information. Because the UpdateParameters collection contains a ControlParameter object that is bound to the selected value of the DropDownList, the button that raises the Update operation is enabled only after an employee is selected.
Security Note: |
|---|
| This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview (Visual Studio). |
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.JSL" Assembly="Samples.AspNet.JSL" %>
<%@ Page language="VJ#" %>
<%@ Import namespace="Samples.AspNet.JSL" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
// Add parameters and initialize the user interface
// only if an employee is selected.
private void Page_Load(Object sender, EventArgs e) throws NorthwindDataException
{
// Be sure the text boxes are initialized with
// data from the currently selected employee.
NorthwindEmployee selectedEmployee =
EmployeeLogic.GetEmployee(DropDownList1.get_SelectedValue());
if (selectedEmployee != null) {
AddressBox.set_Text(selectedEmployee.get_Address());
CityBox.set_Text(selectedEmployee.get_City());
PostalCodeBox.set_Text(selectedEmployee.get_PostalCode());
Button1.set_Enabled(true);
}
else {
Button1.set_Enabled(false);
}
} //Page_Load
// Press the button to update.
private void Btn_UpdateEmployee(Object sender, CommandEventArgs e)
{
ObjectDataSource2.Update();
} //Btn_UpdateEmployee
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ObjectDataSource - VJ# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<!-- The DropDownList is bound to the first ObjectDataSource. -->
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployees"
typename="Samples.AspNet.JSL.EmployeeLogic" />
<p><asp:dropdownlist
id="DropDownList1"
runat="server"
datasourceid="ObjectDataSource1"
datatextfield="FullName"
datavaluefield="EmpID"
autopostback="True" /></p>
<!-- The second ObjectDataSource performs the Update. This
preserves the state of the DropDownList, which otherwise
would rebind when the DataSourceChanged event is
raised as a result of an Update operation. -->
<asp:objectdatasource
id="ObjectDataSource2"
runat="server"
updatemethod="UpdateEmployeeWrapper"
typename="Samples.AspNet.JSL.EmployeeLogic">
<updateparameters>
<asp:controlparameter name="anID" controlid="DropDownList1" propertyname="SelectedValue" />
<asp:formparameter name="anAddress" formfield="AddressBox" />
<asp:formparameter name="aCity" formfield="CityBox" />
<asp:formparameter name="aPostalCode" formfield="PostalCodeBox" />
</updateparameters>
</asp:objectdatasource>
<p><asp:textbox
id="AddressBox"
runat="server" /></p>
<p><asp:textbox
id="CityBox"
runat="server" /></p>
<p><asp:textbox
id="PostalCodeBox"
runat="server" /></p>
<asp:button
id="Button1"
runat="server"
text="Update Employee"
oncommand="Btn_UpdateEmployee" />
</form>
</body>
</html>
The following code example shows the EmployeeLogic class that is used in the preceding code example.
package Samples.AspNet.JSL;
import System.*;
import System.Collections.*;
import System.Configuration.*;
import System.Data.*;
import System.Data.SqlClient.*;
import System.Web.UI.*;
import System.Web.UI.WebControls.*;
//
// EmployeeLogic is a stateless business object that encapsulates
// the operations one can perform on a NorthwindEmployee object.
//
public class EmployeeLogic
{
// Returns a collection of NorthwindEmployee objects.
public static ICollection GetAllEmployees() throws NorthwindDataException
{
ArrayList al = new ArrayList();
// Use the SqlDataSource class to wrap the
// ADO.NET code required to query the database.
ConnectionStringSettings cts =
ConfigurationManager.get_ConnectionStrings().
get_Item("NorthwindConnection");
SqlDataSource sds = new SqlDataSource(cts.get_ConnectionString(),
"SELECT EmployeeID FROM Employees");
try {
IEnumerable ids = sds.Select(DataSourceSelectArguments.get_Empty());
// Iterate through the Enumeration and create a
// NorthwindEmployee object for each ID.
IEnumerator enumerator = ids.GetEnumerator();
while (enumerator.MoveNext()) {
// The IEnumerable contains DataRowView objects.
DataRowView row = (DataRowView)enumerator.get_Current();
String idObj = row.get_Item("EmployeeID").ToString();
NorthwindEmployee nwe = new NorthwindEmployee(idObj);
// Add the NorthwindEmployee object to the collection.
al.Add(nwe);
}
}
finally {
// If anything strange happens, clean up.
sds.Dispose();
}
return al;
} //GetAllEmployees
public static NorthwindEmployee GetEmployee(Object anID)
throws NorthwindDataException
{
ArrayList al = (ArrayList)GetAllEmployees();
IEnumerator enumerator = al.GetEnumerator();
while (enumerator.MoveNext()) {
// The IEnumerable contains initialized NorthwindEmployee objects.
NorthwindEmployee ne = (NorthwindEmployee)enumerator.get_Current();
if (ne.get_EmpID().Equals(anID.ToString())) {
return ne;
}
}
return null;
} //GetEmployee
public static void UpdateEmployee(NorthwindEmployee ne)
throws NorthwindDataException
{
boolean retVal = ne.Update();
if (!(retVal)) {
throw new NorthwindDataException("Employee update failed.");
}
} //UpdateEmployee
// This method is added as a conveniece wrapper on the original
// implementation.
public static void UpdateEmployeeWrapper(String anID, String anAddress,
String aCity, String aPostalCode) throws NorthwindDataException
{
NorthwindEmployee ne = new NorthwindEmployee(anID);
ne.set_Address(anAddress);
ne.set_City(aCity);
ne.set_PostalCode(aPostalCode);
UpdateEmployee(ne);
} //UpdateEmployeeWrapper
// And so on...
} //EmployeeLogic
public class NorthwindEmployee
{
public NorthwindEmployee(Object anID) throws NorthwindDataException
{
this.id = anID;
ConnectionStringSettings cts =
ConfigurationManager.get_ConnectionStrings().
get_Item("NorthwindConnection");
SqlConnection conn = new SqlConnection(cts.get_ConnectionString());
SqlCommand sc = new SqlCommand(" SELECT FirstName,LastName,Address,"
+ "City,PostalCode " + " FROM Employees "
+ " WHERE EmployeeID = @empId", conn);
// Add the employee ID parameter and set its value.
sc.get_Parameters().Add(new SqlParameter("@empId", SqlDbType.Int)).
set_Value(anID.ToString());
SqlDataReader sdr = null;
try {
conn.Open();
sdr = sc.ExecuteReader();
// This is not a while loop. It only loops once.
if (sdr != null && sdr.Read()) {
// The IEnumerable contains DataRowView objects.
this.firstName = sdr.get_Item("FirstName").ToString();
this.lastName = sdr.get_Item("LastName").ToString();
this.address = sdr.get_Item("Address").ToString();
this.city = sdr.get_Item("City").ToString();
this.postalCode = sdr.get_Item("PostalCode").ToString();
}
else {
throw new NorthwindDataException("Data not loaded for"
+ " employee id.");
}
}
finally {
try {
if (sdr != null) {
sdr.Close();
}
conn.Close();
}
catch (SqlException exp) {
// Log an event in the Application Event Log.
}
}
} //NorthwindEmployee
private Object id;
/** @property
*/
public Object get_EmpID()
{
return id;
} //get_EmpID
private String lastName;
/** @property
*/
public void set_LastName(String value)
{
lastName = value;
} //set_LastName
private String firstName;
/** @property
*/
public void set_FirstName(String value)
{
firstName = value;
} //set_FirstName
/** @property
*/
public String get_FullName()
{
return firstName + " " + lastName;
} //get_FullName
private String address;
/** @property
*/
public String get_Address()
{
return address;
} //get_Address
/** @property
*/
public void set_Address(String value)
{
address = value;
} //set_Address
private String city;
/** @property
*/
public String get_City()
{
return city;
} //get_City
/** @property
*/
public void set_City(String value)
{
city = value;
} //set_City
private String postalCode;
/** @property
*/
public String get_PostalCode()
{
return postalCode;
} //get_PostalCode
/** @property
*/
public void set_PostalCode(String value)
{
postalCode = value;
} //set_PostalCode
public boolean Update()
{
// Implement Update logic.
return true;
} //Update
} //NorthwindEmployee
public class NorthwindDataException extends Exception
{
public NorthwindDataException(String msg)
{
super(msg);
} //NorthwindDataException
} //NorthwindDataException
Note: