void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack) { // 創建數據庫連接字符串和SQL語句 string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"]; string query = "SELECT * FROM Products"; // 執行數據庫語句並填充數據到 DataTable 中 SqlCommand myCommand = new SqlCommand(query, new SqlConnection(ConnStr)); SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand); DataTable dt = new DataTable(); myAdapter.Fill(dt); // 數據綁定 DropDownList 控件 DropDownList1.DataSource = dt; DropDownList1.DataTextField = "ProductName"; DropDownList1.DataValueField = "UnitPrice"; DropDownList1.DataBind(); } }
出處:http://mjgforever.cnblogs.com/