SqlDataReader dr; void Page_Load(object sender, System.EventArgs e) { // 數據連接字符串及 SQL 語句 string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"]; string query = "SELECT * FROM Categories"; // 創建並打開數據庫連接 SqlCommand myCommand = new SqlCommand(query, new SqlConnection(ConnStr)); myCommand.Connection.Open(); // 執行數據庫操作並返回 DataReader 對象 dr = myCommand.ExecuteReader(); // 將 DataReader 做為數據源綁定到 DataGrid DataGrid1.DataSource = dr; DataGrid1.DataBind(); // 關閉 DataReader 對象和數據庫連接 dr.Close(); myCommand.Connection.Close(); }
出處:http://mjgforever.cnblogs.com/