要清除流:
您需要创建一个仅用于从数据库获取数据或更新数据的类
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();
}