2016-11-10 28 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?

希望这有助于。