在page_load填充的访问数据集

时间:2017-10-06 16:38:22

标签: c# asp.net .net

我有一个数据集,我在Page_Load事件中填充了两个sql表。我用我的DropDownList ddlAirport00填充第一个表的值。但是我无法从ddlAirport00_SelectedIndexChanged()访问填充的数据集。它就像数据集为空或变量范围有问题。 有人可以帮帮我吗?

        public partial class _Default : System.Web.UI.Page
    {
        public DataSet ds = new DataSet();

    }

my Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            String CS = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
            using (SqlConnection scon = new SqlConnection(CS))
            {
                //this.ds = new DataSet();
                sda = new SqlDataAdapter("Select * from Aeropuerto", scon);
                sda.Fill(ds, "Aeropuerto");

                sda = new SqlDataAdapter("Select * from ALocalidad", scon);
                sda.Fill(ds, "Localidad");

                sda = new SqlDataAdapter("Select * from Tramo", scon);
                sda.Fill(ds, "Tramo");
            }
}

我的DDL SelectedIndexChanged()**我用Ajax来改变testeeric.Text

 protected void ddlAirport00_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ds.Tables.Contains("Tramo"))
        {
               testeeric.Text = DateTime.Now.ToString();
        }
        else
        {
            testeeric.Text = "Brasil";
        }
}

1 个答案:

答案 0 :(得分:1)

由于数据检索逻辑位于if (!IsPostBack)内,因此仅在初始页面加载时调用它。

因此,您需要在SelectedIndexChanged事件中再次从数据库中检索数据。

protected void ddlAirport00_SelectedIndexChanged(object sender, EventArgs e)
{
   String CS = CnfigurationManager.ConnectionStrings
       ["MyDatabaseConnectionString1"].ConnectionString;
   using (SqlConnection scon = new SqlConnection(CS))
   {
      sda = new SqlDataAdapter("Select * from Tramo", scon);
      sda.Fill(ds, "Tramo");

      // Do something.

      if (ds.Tables.Contains("Tramo"))
      {
          testeeric.Text = DateTime.Now.ToString();
      }
      else
      {
          testeeric.Text = "Brasil";
      }
   }
}