使用ObjectDataSource----显示业务对象

 如果要显示业务对象,首先需要业务对象。我创建了两个业务对象来储存个人信息:
ObjectDataSource显+GridView示。Person类和PersonCpllection类,其中Person类有Id、Firstname和Lastname属性,PersonCpllection类基于泛型。

//Person.cs

using  System;

public   class  Person  {

    
private int id;
    
private string firstname;
    
private string lastname;

    
public Person(int id, string firstname, string lastname) {
        
this.id = id;
        
this.firstname = firstname;
        
this.lastname = lastname;
    }


    
public int Id {
        
get return this.id; }
        
set this.id = value; }
    }


    
public string Firstname {
        
get return this.firstname; }
        
set this.firstname = value; }
    }


    
public string Lastname {
        
get return this.lastname; }
        
set this.lastname = value; }
    }

}

//PersonCpllection.cs

using  System;
using  System.Collections.Generic;

public   class  PersonCollection : List < Person >   {

    
public void Remove(int id) {
        Person person 
= this.FindPersonById(id);
        
if (person != null{
            
base.Remove(person);
        }

    }


    
public Person FindPersonById(int id) {
        
foreach (Person person in this{
            
if (person.Id.Equals(id)) {
                
return person;
            }

        }

        
return null;
    }

}

ObjectDataSource控件希望接收类的一个限定名,该类负责处理对象。通常这是业务层的类。实现PersonManager类代码如下。SelectPersons()方法创建了一个新的PersonCollection,为其填充数据,然后返回。数据也只应用程序作用域中存储。在后续调用时,数据可以从该作用域中读取。

//PersonManager.cs

using  System;
using  System.Web;

public   class  PersonManager  {

    
private const string personsKey = "persons";

    
public PersonCollection SelectPersons() {
        HttpContext context 
= HttpContext.Current;

        
if (context.Application[personsKey] == null{
            PersonCollection persons 
= new PersonCollection();

            persons.Add(
new Person(0"Patrick""Lorenz"));
            persons.Add(
new Person(1"Micha""Brunnhuber"));
            persons.Add(
new Person(2"Thomas""Ballmeier"));
            context.Application[personsKey] 
= persons;
        }


        
return (context.Application[personsKey] as PersonCollection);
    }

}

把这三个文件放在App_Code文件夹里。(按照书本说放在Code文件夹却不行,Code改为App_Code就可以了)。

现在准备工作已完成。添加ObjectDataSource1并设置属性(TypeName="PersonManager"、SelectMethod="SelectPersons")。

添加GridView并设置属性“选择数据源”=“ObjectDataSource1”。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值