DataTable、List<T>、SqlDataReader、Entity Framework 查詢結果等實作 IEnumerable 或 IListSource 的物件。gridView.DataSource = dataSource;gridView.DataBind();// 後台
string connStr = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
using (var conn = new SqlConnection(connStr))
using (var cmd = new SqlCommand("SELECT Id, Name, Price FROM Products WHERE Category=@cat", conn)) {
cmd.Parameters.AddWithValue("@cat", ddlCategory.SelectedValue);
var dt = new DataTable();
using (var da = new SqlDataAdapter(cmd)) da.Fill(dt);
gvProducts.DataSource = dt;
gvProducts.DataBind();
}
// 前台
AllowPaging="True" PageSize="10" + OnPageIndexChanging 事件重新繫結。AllowSorting="True" + OnSorting 事件切換 SortExpression。TemplateField 內放 Label/DropDownList/Button 實現自訂顯示與編輯。ViewStateMode="Disabled"、使用 ObjectDataSource 配合 SelectCountMethod 僅抓取當頁資料。GridView Class (System.Web.UI.WebControls) | Microsoft Learn
包含完整屬性、方法、事件、範本與最佳實踐,建議收藏查閱。