2016-11-10 66 views
-3

我有一個asp.net網站,我試圖開發,我有一個問題從數據庫中加載數據。它在C#WebForm應用程序中運行正常,我想知道我需要做什麼才能使其在asp.net項目中正常工作,並將結果綁定到要從中選擇的下拉列表。從asp.net內的數據庫訪問C#網站sitie

try 
      { 
       SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder 
       { 
        DataSource = "127.0.0.1", 
        InitialCatalog = "PIIMSDATA", 
        IntegratedSecurity = true 
       }; 
     SqlConnection cs = new SqlConnection(connectionStringBuilder.ToString()); 
       SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Book1 Order by ID", cs); 


       } 
       System.Data.DataTable dt = new System.Data.DataTable(); 
       da.Fill(dt); 

       //DropDownList2.DataSource = ds.Tables[0]; 
       //DropDownList2.DataTextField = "ID"; 
       //DropDownList2.DataValueField = "ID"; 
       //DropDownList2.DataBind(); 
      } 
      catch (Exception ex) 
      { 
       ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex + "');", true); 
       //MessageBox.Show(ex.Message); 
      } 
     } 
+0

你的問題是什麼? – Ash

+0

我取消註釋DropDownList代碼後,它永遠不會填充我的數據庫結果 –

+0

您是否收到某種錯誤?嘗試逐行調試代碼。 – Ash

回答

0

有很多方法可以做到這一點。這裏有一個例子,我曾經嘗試過:

public string connectionString = "Data Source = YOUCANSEEONSQLSERVER; Initial Catalog = DATABASENAME; User Id = sa; Password = sqlpasswordifyouuse"; 

    private void Valetin_Load(object sender, EventArgs e) 
    { 
     OPIDCB.ResetText(); 
     ValetCB.ResetText(); 
     SqlConnection sqlconn = new SqlConnection(pr.connectionString); 
     SqlCommand sqlselect1 = new SqlCommand("Select EmpID, EmpName from Employees.Employee where IDPosition = 'OP'", sqlconn); 
     sqlconn.Open(); 
     SqlDataReader dr1 = sqlselect1.ExecuteReader(); 

     while (dr1.Read()) 
     { 
      ArrayList MyAL = new ArrayList(); 
      ArrayList MyAL2 = new ArrayList(); 
      MyAL.Add(dr1.GetString(0)); 
      MyAL2.Add(dr1.GetString(1)); 
      foreach (string s in MyAL) 
       foreach (string s2 in MyAL2) 
       { 
        OPIDCB.Items.Add(s + " " + s2); 
       } 
      OPIDCB.SelectedIndex = 0; 
     } 
     dr1.Close(); 
     sqlconn.Close(); 

    } 

如果您正在使用的代碼混淆,您可以訪問此鏈接:What is the right way to populate a DropDownList from a database?

希望這有助於。