2017-10-06 17 views
-3

我有一個數據集,我填充了Page_Load事件中的兩個SQL表。我使用第一個表的值填充我的DropDownList ddlAirport00。但是我無法從ddlAirport00_SelectedIndexChanged()訪問填充的數據集。這就像數據集是空的或變量的範圍有問題。 有人可以幫助我嗎?訪問數據集填入page_load

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

    } 

我的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"; 
     } 
} 
+0

請在此添加一些代碼。這將有助於他人理解你的問題。 – IsuruAb

+0

這是經典的asp.net。頁面加載和selectedindexchanged方法有不同的上下文。您必須再次獲取數據集fron db或對緩存進行排序...... –

+0

每次頁面回傳時,都會觸及Page類的新實例。這意味着任何字段(特定於類實例的變量)對於每個請求都是新的。你不能使用它們來保持請求中的值。你要麼需要在某處緩存數據,要麼重新查詢值。 – mason

回答

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"; 
     } 
    } 
} 
+0

我可能會建議展示如何使用一種方法來包含公共邏輯,而不是將邏輯複製/粘貼到多個位置。 – mason

+0

我無法填寫公開數據集並在任何情況下訪問它? – Feijuca

+0

@Feijuca Http狀態較少,所以它不能維護先前請求的數據。如果你想按照你所描述的方式,你不應該在Page_Load事件中使用'if(!IsPostBack)'。 – Win