Exportar (0) Imprimir
Expandir Tudo
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original

ObjectDataSource.Inserting Evento

Occurs before an Insert operation.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (em System.Web. dll)

public event ObjectDataSourceMethodEventHandler Inserting

Handle the Inserting event to perform additional initialization that is specific to your application, to validate the values of parameters, or to change the parameter values before the ObjectDataSource control performs the insert operation.The parameters are available as an IDictionary collection that is accessed by the InputParameters property, which is exposed by the ObjectDataSourceMethodEventArgs object.

Observação:

Se você não estiver familiarizado com os recursos de acesso a dados no ASP.NET 2.0, você deve ler alguns desses tópicos antes de continuar:

Para obter mais informações sobre tratamento de eventos, consulte Consumindo Eventos.

Esta seção contém dois exemplos de código.The first code example demonstrates how to use an ObjectDataSource object with a business object and a DetailsView control to insert data.O Meio exemplo de código fornece um exemplo do middle-tier business Objeto usado no Primeiro exemplo de código.

The following code example demonstrates how to use an ObjectDataSource control with a business object and a DetailsView control to insert data.Initially, the DetailsView displays a new NorthwindEmployee record, along with an automatically generated Insert button.After you enter data into the fields of the DetailsView control, click the Insert button.The InsertMethod property identifies which method performs the insert operation.

In this example, the UpdateEmployeeInfo method is used to perform an insert; however, it requires a NorthwindEmployee parameter to insert the data.For this reason, the collection of strings that the DetailsView control passes automatically is not sufficient.The NorthwindEmployeeInserting delegate is an ObjectDataSourceMethodEventHandler object that handles the Inserting event and enables you to manipulate the input parameters before the Insert operation proceeds.Because the UpdateEmployeeInfo method requires a NorthwindEmployee object as a parameter, one is created using the collection of strings and is added to the InputParameters collection using a parameter name (ne) that the method expects.You might perform steps like these when using an existing middle-tier object as a data source with types and methods that are not designed specifically for use with the ObjectDataSource control.

When the Insert operation is performed, the method that is identified by the InsertMethod property is called.If the Insert method of the object has a method signature that includes parameters, the InsertParameters collection must contain a parameter with names that match the method signature parameters for the Insert method to complete successfully.

<%@ Register TagPrefix= Namespace= Assembly= %>
<%@ Import = %>
<%@ Page language= %>
<!DOCTYPE html PUBLIC "-
    "http:
<script runat=>
  NorthwindEmployeeInserting(object source, ObjectDataSourceMethodEventArgs e)
{
  
  

  IDictionary paramsFromPage = e.InputParameters;

  NorthwindEmployee ne =  NorthwindEmployee();

  ne.FirstName  = paramsFromPage[].ToString();
  ne.LastName   = paramsFromPage[].ToString();
  ne.Title      = paramsFromPage[].ToString();
  ne.Courtesy   = paramsFromPage[].ToString();
  ne.Supervisor = Int32.Parse(paramsFromPage[].ToString());

  paramsFromPage.Clear();
  paramsFromPage.Add(, ne);
}

</script>
<html xmlns="http:
  <head>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id= method= runat=>

        <asp:detailsview
          id=
          runat=
          autogenerateinsertbutton=
          datasourceid=>
        </asp:detailsview>

        <asp:objectdatasource
          id=
          runat=
          selectmethod=
          insertmethod=
          oninserting=
          typename=
          >
          <selectparameters>
            <asp:parameter name= defaultvalue= />
          </selectparameters>
        </asp:objectdatasource>

    </form>
  </body>
</html>


<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.JSL" Assembly="Samples.AspNet.JSL" %>
<%@ Import namespace="Samples.AspNet.JSL" %>
<%@ Page language="VJ#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private void NorthwindEmployeeInserting(Object source,
    ObjectDataSourceMethodEventArgs e)
{
    // The GridView control passes an array of strings in the parameters
    // collection because that is the type it knows how to work with.
    // However, the business object expects a custom type. Build it
    // and add it to the parameters collection.
    IDictionary paramsFromPage = e.get_InputParameters();

    NorthwindEmployee ne =  new NorthwindEmployee();
    ne.set_FirstName(paramsFromPage.get_Item("FirstName").ToString());
    ne.set_LastName (paramsFromPage.get_Item("LastName").ToString());
    ne.set_Title(paramsFromPage.get_Item("Title").ToString());
    ne.set_Courtesy(paramsFromPage.get_Item("Courtesy").ToString());
    ne.set_Supervisor(Int32.Parse(paramsFromPage.
        get_Item("Supervisor").ToString()));

    paramsFromPage.Clear();
    paramsFromPage.Add("ne", ne);
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - VJ# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:detailsview
          id="DetailsView1"
          runat="server"
          autogenerateinsertbutton="True"
          datasourceid="ObjectDataSource1">
        </asp:detailsview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetEmployee"
          insertmethod="UpdateEmployeeInfo"
          oninserting="NorthwindEmployeeInserting"
          typename="Samples.AspNet.JSL.EmployeeLogic" >
          <selectparameters>
            <asp:parameter name="anID" defaultvalue="-1" />
          </selectparameters>
        </asp:objectdatasource>

    </form>
  </body>
</html>


O seguinte exemplo de código fornece um exemplo de uma Meio-objeto corporativo camada que o acima usa exemplo de código.O exemplo de código é composto de duas classes básicas:

  • The EmployeeLogic class, which is a stateless class that encapsulates business logic.

  • The NorthwindEmployee class, which is a model class that contains only the basic functionality that is required to load and persist data from the data tier.

An additional NorthwindDataException class is provided as a convenience.Para um Concluir exemplo de trabalho, você deve compilação e usar essas classes.The UpdateEmployeeInfo method is not completely implemented, so you will not insert data into the Northwind Traders database when you experiment with this example.

 Samples.AspNet.CS {

 System;
 System.Collections;
 System.Configuration;
 System.Data;
 System.Data.SqlClient;
 System.Web.UI;
 System.Web.UI.WebControls;
  
  
  
  
    EmployeeLogic {

    
      ICollection GetAllEmployees () {
      ArrayList al =  ArrayList();

      ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings[];

      SqlDataSource sds
        =  SqlDataSource(cts.ConnectionString,
                            );
       {
        IEnumerable IDs = sds.Select(DataSourceSelectArguments.Empty);

        
        
        IEnumerator enumerator = IDs.GetEnumerator();
         (enumerator.MoveNext()) {
          
          DataRowView row = enumerator.Current  DataRowView;
          string id = row[].ToString();
          NorthwindEmployee nwe =  NorthwindEmployee(id);
          
          al.Add(nwe);
        }
      }
       {
        
        sds.Dispose();
      }

       al;
    }

      NorthwindEmployee GetEmployee(object anID) {
       (anID.Equals() ||
          anID.Equals(DBNull.Value) ) {
          NorthwindEmployee();
      }
       {
          NorthwindEmployee(anID);
      }
    }

       UpdateEmployeeInfo(NorthwindEmployee ne) {
       retval = ne.Save();
       (! retval) {   NorthwindDataException(); }
    }

       DeleteEmployee(NorthwindEmployee ne) {
       retval = ne.Delete();
       (! retval) {   NorthwindDataException(); }
    }

    
  }

    NorthwindEmployee {

     NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = ;
      firstName = ;
      title=;
      titleOfCourtesy = ;
      reportsTo = -1;
    }

     NorthwindEmployee (object anID) {
      .ID = anID;

      SqlConnection conn
        =  SqlConnection (ConfigurationManager.ConnectionStrings[].ConnectionString);
      SqlCommand sc =
         SqlCommand( +
                        +
                       ,
                       conn);
      
      sc.Parameters.Add( SqlParameter(,SqlDbType.Int)).Value = Int32.Parse(anID.ToString());
      SqlDataReader sdr = ;

       {
        conn.Open();
        sdr = sc.ExecuteReader();

        
         (sdr !=  && sdr.Read()) {
          
          .firstName        = sdr[].ToString();
          .lastName         = sdr[].ToString();
          .title            = sdr[].ToString();
          .titleOfCourtesy  = sdr[].ToString();
           (! sdr.IsDBNull(4)) {
            .reportsTo        = sdr.GetInt32(4);
          }
        }
         {
            NorthwindDataException();
        }
      }
       {
         {
           (sdr != ) sdr.Close();
          conn.Close();
        }
         (SqlException) {
          
          ;
        }
      }
    }

     object ID;
     string EmpID {
       {  ID.ToString();  }
    }

     string lastName;
     string LastName {
       {  lastName; }
       { lastName = value; }
    }

     string firstName;
     string FirstName {
       {  firstName; }
       { firstName = value;  }
    }

     string FullName {
       {  FirstName +  + LastName; }
    }

     string title;
     String Title {
       {  title; }
       { title = value; }
    }

     string titleOfCourtesy;
     string Courtesy {
       {  titleOfCourtesy; }
       { titleOfCourtesy = value; }
    }

         reportsTo;
      Supervisor {
       {  reportsTo; }
       { reportsTo = value; }
    }

      Save () {
      
       ;
    }

      Delete () {
      
       ;
    }
  }

    NorthwindDataException: Exception {
     NorthwindDataException(string msg) :  (msg) { }
  }
}


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 you can perform on a NorthwindEmployee object.
//
public class EmployeeLogic
{    
    // Returns a collection of NorthwindEmployee objects.
    public static ICollection GetAllEmployees() throws
        NorthwindDataException, SqlException
    {
        ArrayList al =  new ArrayList();

		ConnectionStringSettings cts = 
			ConfigurationManager.get_ConnectionStrings().
			get_Item("NorthwindConnection");
			//ConfigurationSettings.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 id = row.get_Item("EmployeeID").ToString();
                NorthwindEmployee nwe =  new NorthwindEmployee(id);
                // 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, SqlException
    {
        if (anId.Equals("-1") || anId.Equals(DBNull.Value)) {
            return new NorthwindEmployee();
        }
        else {
            return new NorthwindEmployee(anId);
        }
    } //GetEmployee

    public static void UpdateEmployeeInfo(NorthwindEmployee ne) throws 
        NorthwindDataException
    {
        boolean retval = ne.Save();
        if (!retval) {
            throw new NorthwindDataException("UpdateEmployee failed.");
        }
    } //UpdateEmployeeInfo

    public static void DeleteEmployee(NorthwindEmployee ne) throws 
        NorthwindDataException
    {
        boolean retval = ne.Delete();
        if (!retval) {
            throw new NorthwindDataException("DeleteEmployee failed.");
        }
    } //DeleteEmployee

    // And so on...
} //EmployeeLogic

public class NorthwindEmployee 
{
    public NorthwindEmployee() 
    {
        id = DBNull.Value;
        lastName = "";
        firstName = "";
        title = "";
        titleOfCourtesy = "";
        reportsTo =-1;
    } //NorthwindEmployee

    public NorthwindEmployee(Object anId) throws 
        NorthwindDataException ,SqlException
    {
        this.id = anId;
			

		SqlConnection conn = new SqlConnection(ConfigurationManager.
			get_ConnectionStrings().get_Item("NorthwindConnection").get_ConnectionString());
         SqlCommand sc =  new SqlCommand(
            " SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " 
            + " 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();
            // Only loop 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.title = sdr.get_Item( "Title").ToString();
                this.titleOfCourtesy = sdr.get_Item( "TitleOfCourtesy").
                    ToString();
                if (!(sdr.IsDBNull(4))) {
                    this.reportsTo = sdr.GetInt32(4);
                }
            }
            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.
            throw exp;
            }
        }
    } //NorthwindEmployee

    private Object id;

    /** @property 
     */
    public String get_EmpID()
    {
        return id.ToString();
    } //get_EmpID

    private String lastName;

      /** @property 
       */
    public String get_LastName()
    {
        return lastName;
    } //get_LastName

    /** @property 
     */
    public void set_LastName (String value)
    {
        lastName = value;
    } //set_LastName

    private String firstName;

    /** @property 
     */
    public String get_FirstName()
    {
        return firstName;
    } //get_FirstName

    /** @property 
     */
    public void set_FirstName (String value)
    {
        firstName = value;
    } //set_FirstName 

    /** @property 
     */
    public String get_FullName()
    {
        return get_FirstName() + " " + get_LastName();
    } //get_FullName

    private String title;

    /** @property 
     */
    public String get_Title()
    {
        return title;
    } //get_Title

    /** @property 
     */
    public void set_Title (String value)
    {
        title = value;
    } //set_Title 

    private String titleOfCourtesy;

    /** @property 
     */
    public String get_Courtesy()
    {
        return titleOfCourtesy;
    } //get_Courtesy

    /** @property 
     */
    public void set_Courtesy (String value)
    {
        titleOfCourtesy = value;
    } //set_Courtesy 

    private int reportsTo;

    /** @property 
     */
    public int get_Supervisor()
    {
        return reportsTo;
    }//get_Supervisor

    /** @property 
     */
    public void set_Supervisor (int value)
    {
        reportsTo = value;
    } //set_Supervisor 

    public boolean Save() 
    {
        // Implement persistence logic.
        return true;
    } //Save

    public boolean Delete() 
    {
        // Implement delete logic.
        return true;
    } //Delete
} //NorthwindEmployee

public class NorthwindDataException extends System.Exception
{
    public NorthwindDataException(String msg)
    {
         super(msg);
    } //NorthwindDataException
} //NorthwindDataException


Contribuições da comunidade

ADICIONAR
Mostrar:
© 2014 Microsoft