0

我在我的 aspx 代码后面有一个名为 PhotoDatabinding 的公共方法,它的作用是将数据库绑定到列表视图控件。

public void PhotoDatabinding()
{


lnqPhotoDataContext dbCon = new lnqPhotoDataContext();
var res = from p in dbCon.Photos orderby p.PhotoID descending select new {          p.PhotoID, p.FileName };

    lvSubAlbumDB.DataSource = res;
    lvSubAlbumDB.DataBind();

 }

现在,在我的名为 Process 的公共类中,我有一个名为 UpdateSave 的方法。我的问题是如何访问 PhotoBinding 方法,使其看起来像这样

public class Process
{
public UpdateSave()
{
    ....some code
    PhotoDatabinding();

}

}

感谢并感谢您的所有帮助和建议。

4

1 回答 1

1

要清除流:

您需要创建一个仅用于从数据库获取数据或更新数据的类

public class PhotoAccess
{

  public class PhotoInfo
  {
    public int PhotoID {get; set;}
    public string FileName {get; set;}
  }

  public IEnumerable<PhotoInfo> GetPhotos()
  {
   using ( var dbCon = new lnqPhotoDataContext())
   {
      var res = from p in dbCon.Photos 
            orderby p.PhotoID descending 
            select new PhotoInfo 
                       {
                          p.PhotoID, 
                          p.FileName 
                       };
      return res.AsEnumerable();
    }
  }
  public bool UpdateSave(...)
  {
      ... code to do update or save, use here only classes for working with the DB
  }
}

然后在页面后面的代码中

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
       var dataAccess = new PhotoAccess();
       var items = dataAccess.GetPhotos();

       lvSubAlbumDB.DataSource = items;
       lvSubAlbumDB.DataBind();
   }
}
protected void btSave_OnClick(object sender, EventArgs e)
{
    var dataAccess = new PhotoAccess();
    dataAccess.UpdateSave(...pass here the parameters or an object which is going to be inserted);

    var items = dataAccess.GetPhotos();

    lvSubAlbumDB.DataSource = items;
    lvSubAlbumDB.DataBind();
}

您还可以将绑定代码重构为 Page 类的另一个方法

private void BindAlbum()
{
   var dataAccess = new PhotoAccess();
   var items = dataAccess.GetPhotos();    

   lvSubAlbumDB.DataSource = items;
   lvSubAlbumDB.DataBind();
}

页面加载将是:

 protected void Page_Load(object sender, EventArgs e)
    {
       if (!Page.IsPostBack)
       {
           BindAlbum();
       }
    }

和更新处理程序

 protected void btSave_OnClick(object sender, EventArgs e)
    {
        var dataAccess = new PhotoAccess();
        dataAccess.UpdateSave(...pass here the parameters or an object which is going to be inserted);

        BindAlbum();
    }
于 2012-04-25T15:07:48.570 回答