Материал из .Net Framework эксперт
Add DataColumn to DataTable
<%@ Page Language="C#" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
IEnumerable ItemsInCart()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("ProductID", typeof(int)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Price", typeof(float)));
for (int i = 0; i < 10; i++)
{
dr = dt.NewRow();
dr[0] = i+1;
dr[1] = "Item " + i.ToString();
dr[2] = (float) 1.2 * i;
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
string GetProductDescription(int ID)
{
return "This is the description for product " + ID.ToString() + "...";
}
void BindData()
{
dgCart.DataSource = ItemsInCart();
dgCart.DataBind();
}
void dgCart_ItemCommand(object sender, DataGridCommandEventArgs e)
{
Response.Write("A button was clicked...");
}
</script>
<form runat="server">
<asp:DataGrid runat="server" id="dgCart"
AutoGenerateColumns="False"
Font-Name="Verdana"
Font-Size="8pt"
OnItemCommand="dgCart_ItemCommand">
<HeaderStyle HorizontalAlign="Center"
Font-Bold="True"
Font-Size="11pt"
BackColor="Navy"
ForeColor="White" />
<Columns>
<asp:ButtonColumn Text="Remove"
ButtonType="PushButton"
HeaderText="Remove" />
<asp:ButtonColumn Text="Details"
ButtonType="PushButton"
HeaderText="Details" />
<asp:BoundColumn DataField="Name" HeaderText="Product Name" />
<asp:BoundColumn DataField="Price"
HeaderText="Price"
ItemStyle-HorizontalAlign="right"
DataFormatString="{0:c}" />
</Columns>
</asp:DataGrid>
</form>