<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<title>DataGrid ButtonColumn Example</title>
<link rel="stylesheet" href="/shared/netdemos.css">
<script language="C#" runat="server" src="fetchData_sql.cs" />
<script language="C#" runat="server">
DataTable Cart;
DataView CartView;
void Page_Load ( Object src, EventArgs e ) {
if ( !IsPostBack ) {
string query = "SELECT * FROM Titles where Price > 0";
myGrid.DataSource = fetchData ( query );
myGrid.DataBind ( );
}
if ( Session [ "shoppingSession" ] == null ) {
Cart = new DataTable ( );
Cart.Columns.Add ( new DataColumn ( "Item", typeof ( string ) ) );
Cart.Columns.Add ( new DataColumn ( "Price", typeof ( string ) ) );
Session [ "shoppingSession" ] = Cart;
}
else Cart = ( DataTable ) Session [ "shoppingSession" ];
CartView = new DataView ( Cart );
shopCart.DataSource = CartView;
shopCart.DataBind ( );
}
void updateCart ( Object src, DataGridCommandEventArgs e ) {
DataRow dr = Cart.NewRow ( );
// e.Item is the row of the table where the command is raised.
// for bound columns, values are stored in the Text property of Cells [ colIndex ]
string item = e.Item.Cells [ 1 ].Text;
string price = e.Item.Cells [ 2 ].Text;
if ( ( ( LinkButton ) e.CommandSource ).CommandName == "AddToCart" ) {
dr [ 0 ] = item; dr [ 1 ] = price;
Cart.Rows.Add ( dr );
}
else { // remove from Cart
CartView.RowFilter = "Item='" + item + "'";
if ( CartView.Count > 0 ) CartView.Delete ( 0 );
CartView.RowFilter = "";
}
shopCart.DataBind ( );
}
</script>
</head>
<body>
<!-- #include virtual="~/shared/top.inc" -->
<div class="header"><h2>DataGrid ButtonColumn Example</h2></div>
<hr size=1 width=92%>
<form runat="server">
<table cellpadding="5">
<tr valign="top">
<td><b>Product List</b>
<asp:datagrid id="myGrid" runat="server"
cellpadding=5 font-size="9pt"
gridlines="horizontal"
headerstyle-backcolor="slategray"
headerstyle-forecolor="ivory"
headerstyle-font-bold
itemstyle-verticalalign="top"
autogeneratecolumns=false
onItemCommand="updateCart">
<columns>
<asp:boundcolumn
headertext="Title"
datafield="title" />
<asp:boundcolumn
headertext="Item"
datafield="title_id" />
<asp:boundcolumn
headertext="Price"
datafield="price"
dataformatstring="{0:c}"
itemstyle-horizontalalign="right" />
<asp:buttoncolumn
text="Add"
commandname="AddToCart" />
<asp:buttoncolumn
text="Remove"
commandname="RemoveFromCart" />
</columns>
</asp:datagrid>
</td>
<td><b>Shopping Cart</b>
<asp:datagrid id="shopCart" runat="server"
cellpadding=5 font-size="9pt"
headerstyle-backcolor="slategray"
headerstyle-forecolor="ivory"
headerstyle-font-bold
itemstyle-verticalalign="top" />
</td></tr>
</table>
</form>
<hr size=1 width=92%>
<!-- #include virtual="~/shared/viewsrc.inc" -->
</body>
</html>