private DataTable createProductDT()
{
DataTable dtProducts = new DataTable();
DataColumn productColumn = new DataColumn();
productColumn.DataType = System.Type.GetType("System.Int32");
productColumn.ColumnName = "id";
productColumn.Unique = true;
dtProducts.Columns.Add(productColumn);
productColumn = new DataColumn();
productColumn.DataType = System.Type.GetType("System.String");
productColumn.ColumnName = "thumb";
dtProducts.Columns.Add(productColumn);
productColumn = new DataColumn();
productColumn.DataType = System.Type.GetType("System.String");
productColumn.ColumnName = "name";
dtProducts.Columns.Add(productColumn);
productColumn = new DataColumn();
productColumn.DataType = System.Type.GetType("System.Double");
productColumn.ColumnName = "price";
dtProducts.Columns.Add(productColumn);
productColumn = new DataColumn();
productColumn.DataType = System.Type.GetType("System.Int32");
productColumn.ColumnName = "quantity";
dtProducts.Columns.Add(productColumn);
//使"id"成为主键
DataColumn[] pkColumns = new DataColumn[1];
pkColumns[0] = dtProducts.Columns["id"];
dtProducts.PrimaryKey = pkColumns;
return dtProducts;
}
private void populateProducts()
{
//创建基本结构
DataTable dtProducts = createProductDT();
//把产品添加到其上
//创建初始的行
DataRow aProduct = dtProducts.NewRow();
aProduct["id"] = 11;
aProduct["thumb"] = "images/widget0.jpg";
aProduct["name"] = "Red Widget";
aProduct["price"] = 19.99;
dtProducts.Rows.Add(aProduct);
//重用该行以添加新产品
aProduct = dtProducts.NewRow();
aProduct["id"] = 22;
aProduct["thumb"] = "images/widget1.jpg";
aProduct["name"] = "Green Widget";
aProduct["price"] = 50.99;
dtProducts.Rows.Add(aProduct);
//把DataTable绑定到产品GridView
gvProducts.DataSource = dtProducts;
gvProducts.DataBind();
//把产品存储到Session
Session["dtProducts"] = dtProducts;
}
gvProducts.DataSource = dtProducts;
gvProducts.DataBind();
DataKeyNames="id"
EmptyDataText="~Basket is empty~"