我想用个全局的ds,但是对ds的赋值需要写在一个事件里面,这样我在其他地方调用ds的时候里面就没有数据了,请问该如何处理?如下例(只是例子):
public DataSet ds = new DataSet();private void Button1_Click(object sender, System.EventArgs e)
{
DBProcess db = new DBProcess("ConnectString");
db.Open();
ds = db.ExecuteDataSet("select * from intno",null);
db.Close();
int i = ds.Tables[0].Rows.Count;
} private void Button2_Click(object sender, System.EventArgs e)
{
int i= ds.Tables[0].Rows.Count;
int j= ds.Tables[0].Rows.Count;
}注:因为查询数据库有条件,所以只能写在事件里
public DataSet ds = new DataSet();private void Button1_Click(object sender, System.EventArgs e)
{
DBProcess db = new DBProcess("ConnectString");
db.Open();
ds = db.ExecuteDataSet("select * from intno",null);
db.Close();
int i = ds.Tables[0].Rows.Count;
} private void Button2_Click(object sender, System.EventArgs e)
{
int i= ds.Tables[0].Rows.Count;
int j= ds.Tables[0].Rows.Count;
}注:因为查询数据库有条件,所以只能写在事件里
应该打消这种想法.
{
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ds = new DataSet();
ViewState["DS"] = ds;
}
}
protected void cmdSend_Click(object sender, EventArgs e)
{
if (ViewState["DS"] != null)
{
ds = ViewState["DS"] as DataSet;
}
}
}
要是只在同一个会话中用,就用Session存起来.
要全局用.那就用application存一下.
private void Button1_Click(object sender, System.EventArgs e)
{
DataTable dt = null;
if (ViewState["dt"] != null)
{
DBProcess db = new DBProcess("ConnectString");
db.Open();
ds = db.ExecuteDataSet("select * from intno", null);
db.Close();
}
else
{
DBProcess db = new DBProcess("ConnectString");
db.Open();
ds = db.ExecuteDataSet("select * from intno", null);
db.Close();
}
ViewState["dt"] = dt;
} private void Button2_Click(object sender, System.EventArgs e)
{
DataTable dt=(DataTable )ViewState["dt"];
int i = dt.Rows.Count;
int j = dt.Rows.Count;
}隨手寫的,你修改一下。
复杂点的话,可以做成单利模式的
public static DataSet GetDataSet()
{
if(getDataSet==null)
{
getDataSet=...}return getDataSet;
}