public partial class _Default : System.Web.UI.Page 
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
    DataSet dsPlant = new DataSet();
    SqlDataAdapter sdap = new SqlDataAdapter();
    SqlCommand sc = new SqlCommand();    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int i = 0;
            if (con.State == ConnectionState.Closed)
                con.Open();
            try
            {                sc.CommandText = "select plname,OrderNo from GS_pl_Plant order by plorderby,orderno";
                sc.Connection = con;
                sdap.SelectCommand = sc;
                sdap.Fill(dsPlant,"plant");
            }
            finally
            {
                con.Close();
            }
            DropDownList1.Items.Clear();
            for (i = 0; i <= dsPlant.Tables[0].Rows.Count - 1; i++)
            {
                DropDownList1.Items.Add(dsPlant.Tables[0].Rows[i][0].ToString());
            }
        }
    }
 
    protected void Button2_Click(object sender, EventArgs e)
    {
        //int si = DropDownList1.SelectedIndex;
        Label3.Text = dsPlant.Tables[0].Rows[3][0].ToString();  //此处发生错误
        
    }
}(本人刚从DELPHI转C#,刚开始写程序就遇到了问题,求解决)
    上面程序中是做一个查询,然后添加到DropDownList,由于DropDownList显示字段并不是键字段,于是我想根据DropDownList1.SelectedIndex去访问DATASET中的对应行。
    访问时发生了一个错误,“无法找到表 0”,我知道是表填充后被提前释放了,请教要怎样我在Button2的时候才能引用,也就是该DataTable在该页面的全局有效,不要在设计期添加DATASET的情况下。先谢过了!

解决方案 »

  1.   

    ASP.NET特殊,因为http协议(连接就断开),Response结束,这个Page对象就被销毁了,然后服务端会为每个Request重新创建一个Page对象,Button点击的时候的之前类实例已经没有了。所以就算你定义类成员,在Button点击事件时,你拿到的DataSet实例是null。两个办法:1,把DataSet放到ViewState里,2,重新查一遍。
      

  2.   

    楼上正解,或者把if (!IsPostBack)去掉试试。(就是说先保证查询有结果)
      

  3.   

    感谢 JustACoder 的回答,我明白了,真没想到HTTP把PAGE刷新得这么彻底!
    不知道能不能给我推荐本好书?
      

  4.   

    楼主看看 asp.net  页面生存周期咯。。