ObjectDataSourceMethodEventArgs的InputParameters 属性

 

如果使用 ObjectDataSourceMethodEventHandler 对象处理 SelectingUpdatingInsertingDeleting 事件,则可以使用 InputParameters 属性访问和操作这些参数。此字典中参数的任何更改都将影响到为操作所调用的方法重载。当设置了 ObjectDataSource 控件的 DataObjectTypeName 属性时,只能修改此字典中各项的数据对象属性,而不能添加或移除参数

 

下面的代码示例演示如何使用 DropDownList 控件、TextBox 控件和多个 ObjectDataSource 控件更新数据。DropDownList 显示一个 Northwind Employee 的名称,而 TextBox 控件用于输入和更新地址信息。由于 UpdateParameters 属性包含绑定到 DropDownList 控件的选定值的 ControlParameter 对象,因此只有在选中一个雇员后才能启用触发 Update 方法的按钮。

在此示例中,在 Update 方法之前调用 NorthwindEmployeeUpdating 方法,以便将正确的参数和值添加到 InputParameters 集合。可以通过动态方式(如演示所示)或声明方式添加参数和值。

代码
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> <% @ Register TagPrefix = " aspSample "  Namespace = " Samples.AspNet.CS "  Assembly = " Samples.AspNet.CS "   %>
<% @ Page language = " c# "   %>
<% @ Import  namespace = " Samples.AspNet.CS "   %>
< Script runat = " server " >

//  Add parameters and initialize the user interface
//  only if an employee is selected.
private   void  Page_Load( object  sender, EventArgs e)
{
  
//  Be sure the text boxes are initialized with
  
//  data from the currently selected employee.
  NorthwindEmployee selectedEmployee  =  EmployeeLogic.GetEmployee(DropDownList1.SelectedValue);
  
if  (selectedEmployee  !=   null ) {
    AddressBox.Text    
=  selectedEmployee.Address;
    CityBox.Text       
=  selectedEmployee.City;
    PostalCodeBox.Text 
=  selectedEmployee.PostalCode;

    Button1.Enabled 
=   true ;
  }
  
else  {
    Button1.Enabled 
=   false ;
  }
}

//  Press the button to update.
private   void  Btn_UpdateEmployee ( object  sender, CommandEventArgs e) {
    ObjectDataSource2.Update();
}

//  Dynamically add parameters to the InputParameters collection.
private   void  NorthwindEmployeeUpdating( object  source, ObjectDataSourceMethodEventArgs e) {

  
//  The names of the parameters are the same as
  
//  the variable names for the method that is invoked to
  
//  perform the Update. The InputParameters collection is
  
//  an IDictionary collection of name/value pairs,
  
//  not a ParameterCollection.
  e.InputParameters.Add( " anID " ,       DropDownList1.SelectedValue);
  e.InputParameters.Add(
" anAddress "   ,AddressBox.Text);
  e.InputParameters.Add(
" aCity "       ,CityBox.Text);
  e.InputParameters.Add(
" aPostalCode " ,PostalCodeBox.Text);
}
</ Script >
< html >
  
< head >
    
< title > ObjectDataSource  -  C# 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.CS.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 "
          onupdating
= " NorthwindEmployeeUpdating "
          typename
= " Samples.AspNet.CS.EmployeeLogic "   />

        
< 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 >

 

 

实例二:

 

本节包含两个代码示例。第一个代码示例演示如何将 ObjectDataSource 控件与业务对象和 DetailsView 控件配合使用来插入数据。第二个代码示例提供了第一个代码示例使用的中间层业务对象示例。

下面的代码示例演示如何将 ObjectDataSource 控件与业务对象和 DetailsView 控件配合使用来插入数据。DetailsView 最初显示一个新的 NorthwindEmployee 记录和一个自动生成的“插入”按钮。将数据输入 DetailsView 控件的字段中后单击“插入”按钮,InsertMethod 属性将标识出执行 Insert 操作的方法。

在此示例中,UpdateEmployeeInfo 方法用于执行插入;然而它需要 NorthwindEmployee 参数才能插入数据。因此,只有 DetailsView 控件自动传递的字符串集合并不够。NorthwindEmployeeInserting 委托是一个 ObjectDataSourceMethodEventHandler 对象,它用于处理 Inserting 事件,并使您能够在 Insert 操作继续进行之前操作输入参数。由于 UpdateEmployeeInfo 方法需要 NorthwindEmployee 对象作为参数,因此使用字符串集合创建了一个这样的对象,并将其添加到 InputParameters 集合。

 

代码
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> <% @ Register TagPrefix = " aspSample "  Namespace = " Samples.AspNet.CS "  Assembly = " Samples.AspNet.CS "   %>
<% @ Import  namespace = " Samples.AspNet.CS "   %>
<% @ Page language = " c# "   %>
< Script runat = " server " >
private   void  NorthwindEmployeeInserting( object  source, ObjectDataSourceMethodEventArgs e)
{
  
//  The business object expects a custom type. Build it
  
//  and add it to the parameters collection.
  
  IDictionary paramsFromPage 
=  e.InputParameters;

  NorthwindEmployee ne 
=   new  NorthwindEmployee();

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

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

</ Script >
< html >
  
< head >
    
< title > ObjectDataSource  -  C# 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.CS.EmployeeLogic "
          
>
          
< selectparameters >
            
< asp:parameter name = " anID "  defaultvalue = " -1 "   />
          
</ selectparameters >
        
</ asp:objectdatasource >

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

下面的代码示例提供了前一代码示例所使用的中间层业务对象的示例。下面的列表描述代码示例中定义的两个主类:

  • EmployeeLogic 类,这是封装业务逻辑的无状态类。

  • NorthwindEmployee 类,这是仅包含从数据层加载和保留数据所需的基本功能的模型类。

此外,提供 NorthwindDataException 类只是为了便于使用。

此组示例类使用 Northwind Traders 数据库,该数据库是 Microsoft SQL Server 和 Microsoft Access 自带的示例数据库。要获得完整的可运行示例,请将这些类放在应用程序根目录下的 App_Code 目录中,或者对它们进行编译并将产生的 DLL 放在 Bin 目录中,以使用这些类。UpdateEmployeeInfo 方法未完全实现,因此在试用此示例时不会将数据插入到 Northwind Traders 数据库中。

 

代码
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> namespace  Samples.AspNet.CS {

using  System;
using  System.Collections;
using  System.Configuration;
using  System.Data;
using  System.Data.SqlClient;
using  System.Web.UI;
using  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 () {
      ArrayList al 
=   new  ArrayList();

      ConnectionStringSettings cts 
=  ConfigurationManager.ConnectionStrings[ " NorthwindConnection " ];

      SqlDataSource sds
        
=   new  SqlDataSource(cts.ConnectionString,
                            
" SELECT EmployeeID FROM Employees " );
      
try  {
        IEnumerable IDs 
=  sds.Select(DataSourceSelectArguments.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  =  enumerator.Current  as  DataRowView;
          
string  id  =  row[ " 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;
    }

    
public   static  NorthwindEmployee GetEmployee( object  anID) {
      
if  (anID.Equals( " -1 " ||
          anID.Equals(DBNull.Value) ) {
        
return   new  NorthwindEmployee();
      }
      
else  {
        
return   new  NorthwindEmployee(anID);
      }
    }

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

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

    
//  And so on...
  }

  
public   class  NorthwindEmployee {

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

    
public  NorthwindEmployee ( object  anID) {
      
this .ID  =  anID;

      SqlConnection conn
        
=   new  SqlConnection (ConfigurationManager.ConnectionStrings[ " NorthwindConnection " ].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.Parameters.Add( new  SqlParameter( " @empId " ,SqlDbType.Int)).Value  =  Int32.Parse(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[ " FirstName " ].ToString();
          
this .lastName          =  sdr[ " LastName " ].ToString();
          
this .title             =  sdr[ " Title " ].ToString();
          
this .titleOfCourtesy   =  sdr[ " 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) {
          
//  Log an event in the Application Event Log.
           throw ;
        }
      }
    }

    
private   object  ID;
    
public   string  EmpID {
      
get  {  return  ID.ToString();  }
    }

    
private   string  lastName;
    
public   string  LastName {
      
get  {  return  lastName; }
      
set  { lastName  =  value; }
    }

    
private   string  firstName;
    
public   string  FirstName {
      
get  {  return  firstName; }
      
set  { firstName  =  value;  }
    }

    
public   string  FullName {
      
get  {  return  FirstName  +   "   "   +  LastName; }
    }

    
private   string  title;
    
public  String Title {
      
get  {  return  title; }
      
set  { title  =  value; }
    }

    
private   string  titleOfCourtesy;
    
public   string  Courtesy {
      
get  {  return  titleOfCourtesy; }
      
set  { titleOfCourtesy  =  value; }
    }

    
private   int     reportsTo;
    
public   int  Supervisor {
      
get  {  return  reportsTo; }
      
set  { reportsTo  =  value; }
    }

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

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

  
internal   class  NorthwindDataException: Exception {
    
public  NorthwindDataException( string  msg) :  base  (msg) { }
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值