你的位置:首页 > ASP.net教程

[ASP.net教程]asp.net:用类来后台绑定数据源


//封装成一个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

/// <summary>
/// bindData 的摘要说明
/// </summary>
public class bindData
{

//声明一个查询语句的参数
private string _selectSQL;

//参数的属性

public string SelectSQL
{
get { return _selectSQL; }
set { _selectSQL = value; }
}

//重写方法
public bindData(string selsql)
{
this._selectSQL = selsql;
}

//带返回值DataView的方法BindDate()

public DataView BindDate(){
string s = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\xlgameguide.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection sqlConnection = new SqlConnection(s);
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(this._selectSQL, s);
DataSet ds = new DataSet();
sqlDataAdapter.Fill(ds, "table");
DataView dv = ds.Tables["table"].DefaultView;
return dv;

}


}

//网页后台代码

protected void Page_Load(object sender, EventArgs e)
{

//必须是在!IsPostBack内,不然每次刷新就会多次重复邦定
if (!IsPostBack)
{

//新建对象bd

bindData bd = new bindData("SELECT * FROM [BBSgame]");

//新建gv用于接收对应的DataView
DataView gv = bd.BindDate();

//数据绑定
ListView1.DataSource = gv;
ListView1.DataBind();
}
}