Changing Output with the ItemCreated Event Using the DataGrid and DataList

You might want to alter the way an item is rendered based on certain criteria, using either the DataGrid or DataList controls. For example, you might have a DataGrid which displays accounting information and you want negative numbers to be red instead of black. You can use the ItemCreated event to accomplish this. This event is fired every time an item is created for either control. Listing 10.4 illustrates how to use this feature in the DataGrid.

Listing 10.4. Using the ItemCreated Event with the DataGrid
[Visual Basic]

01: <%@ import namespace="System.Data" %>
02: <%@ import namespace="System.Data.SqlClient" %>
03: <script language="c#" runat="server">
04:  private string sSqlCon = "server=localhost;uid=sa;pwd=;database=northwind";
05:
06:  public void Page_Load(Object sender, EventArgs e){
07:
08:    if (! IsPostBack){
09:     Bind();
10:    }
11:
12:  }
13:
14: private void Bind() {
15:
16:   SqlConnection SqlCon = new SqlConnection(sSqlCon);
17:   StringBuilder SqlCmd = new StringBuilder();
18:    SqlCmd.Append("SELECT ProductName,UnitPrice,");
19:    SqlCmd.Append("UnitsInStock,UnitsOnOrder,");
20:    SqlCmd.Append("ProductID FROM Products");
21:   SqlDataAdapter sda = new SqlDataAdapter(SqlCmd.ToString(),SqlCon);
22:   DataSet ds = new DataSet();
23:   sda.Fill(ds,"products");
24:   DGProducts.DataSource = ds.Tables["Products"].DefaultView;
25:   DGProducts.DataBind();
26:
27: }
28:
29: public void DGProducts_ItemCreated(Object sender, DataGridItemEventArgs e) {
30:
31:  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType
.AlternatingItem) {
32:   int iUnitsInStock = int.Parse(DataBinder.Eval(e.Item.DataItem, "UnitsInStock")
.ToString());
33:   if (iUnitsInStock <= 10) {
34:    e.Item.Cells[1].ForeColor = System.Drawing.Color.Red;
35   }
36:   }
37:
38:  }
39:
40: </script>
41: <html>
42:   <body>
43:    <head>
44:
45:     <style rel="stylesheet">
46:      H3 {  font: bold 11pt Verdana, Arial, sans-serif; }
47:      .products {  font: 9pt Verdana, Arial, sans-serif; }
48:      .productsHead {  font: bold 9pt Verdana, Arial, sans-serif;
49:       background-color:Maroon; color:white; }
50:      a {  text-decoration:none; }
51:      a:hover {  text-decoration:underline; color:maroon; }
52:    </style>
53:
54:   </head>
55:     <form runat="server">
56: <H3>ItemCreated Example - Visual Basic.NET</H3>
57:
58: <asp:DataGrid
59:  id="DGProducts"
60:  runat="server"
61:  Cellpadding="4" Cellspacing="0" Width="750"
62:  BorderWidth="1" Gridlines="None"
63:  AlternatingItemStyle-BackColor="Tan"
64:  HeaderStyle-CssClass="productsHead"
65:  Font-Size="12"
66:  AutoGenerateColumns="false"
67:  OnItemCreated="DGProducts_ItemCreated"
68:  >
69:  <Columns>
70:  <asp:BoundColumn DataField="ProductName" HeaderText="Product Name" />
71:  <asp:BoundColumn DataField="UnitsInStock" HeaderText="Units in Stock" />
72:  <asp:BoundColumn DataField="UnitsOnOrder" HeaderText="Units on Order" />
73:  <asp:BoundColumn DataField="UnitPrice" HeaderText="Price Per Unit"
74:   DataFormatString="{ 0:C} " ReadOnly="true" />
75:  <asp:BoundColumn DataField="ProductID"
76:   HeaderText="ProductID" visible="false"/>
77:  </columns>
78: </asp:DataGrid>
79:   </form>
80:  </body>
81: </html>
[C#—Replace server code]
01: <%@ import namespace="System.Data" %>
02: <%@ import namespace="System.Data.SqlClient" %>
03: <script language="vb" runat="server">
04:  private sSqlCon as string  = "server=localhost;uid=sa;pwd=;database=northwind"
05:
06:  public sub Page_Load(sender as Object, e as EventArgs)
07:
08:    if not IsPostBack then
09:     Bind()
10:    end if
11:
12:  end sub
13:
14: private sub Bind()
15:
16:   dim SqlCon as new SqlConnection(sSqlCon)
17:   dim SqlCmd as new StringBuilder()
18:    SqlCmd.Append("SELECT ProductName,UnitPrice,")
19:    SqlCmd.Append("UnitsInStock,UnitsOnOrder,")
20:    SqlCmd.Append("ProductID FROM Products")
21:   dim sda as new SqlDataAdapter(SqlCmd.ToString(),SqlCon)
22:   dim ds as new DataSet()
23:   sda.Fill(ds,"products")
24:   DGProducts.DataSource = ds.Tables("Products").DefaultView
25:   DGProducts.DataBind()
26:
27: end sub
28:
29: public sub DGProducts_ItemCreated(sender as Object,e as DataGridItemEventArgs)
30:
31:  if (e.Item.ItemType = ListItemType.Item or e.Item.ItemType = ListItemType
.AlternatingItem) then
32:   dim iUnitsInStock as integer = integer.Parse(DataBinder.Eval(e.Item.DataItem,
 "UnitsInStock").ToString())
33:   if (iUnitsInStock <= 10) then
34:    e.Item.Cells(1).ForeColor = System.Drawing.Color.Red
35:   end if
36:  end if
37:
38: end sub
39:
40: </script>

One of the things to do when you want to use the ItemCreated event is set the OnItemCreated attribute equal to the name of the method that will handle the ItemCreated event (line 67). In this example, it's DGProducts_ItemCreated (lines 29–38) and it expects Object and DataGridItemEventArgs as parameters. DataGridItemEventArgs contains the Item that's going to be added to the container, and you have programmatic access to all its attributes. In our example we are going to check the value of the UnitsInStock field from our data source. If it is equal to 10 or less than that cells ForeColor will be red.

Because the ItemCreated event is fired for each item including the DataGrid's Header and Footer we need to evaluate the item to make sure it is either of the Item or AlternatingItem type (line 31); otherwise you would receive an exception. Figure 10.4 is an illustration of this page.

Figure 10.4. Using the ItemCreated event to change the ForeColor attribute of the item to red if the value of the UnitsInStock field is less than 10.


Listing 10.5 illustrates how to handle the ItemCreated event using the DataList control.

Listing 10.5. Using the ItemCreated Event with the DataList
[Visual Basic]

01: <%@ import namespace="System.Data" %>
02: <%@ import namespace="System.Data.SqlClient" %>
03: <script language="vb" runat="server">
04:  private sSqlCon as string  = "server=localhost;uid=sa;pwd=;database=northwind"
05:
06:  public sub Page_Load(sender as Object, e as EventArgs)
07:
08:    if not IsPostBack then
09:     Bind()
10:    end if
11:
12:  end sub
13:
14: private sub Bind()
15:
16:   dim SqlCon as new SqlConnection(sSqlCon)
17:   dim SqlCmd as new StringBuilder()
18:    SqlCmd.Append("SELECT ProductName,UnitPrice,")
19:    SqlCmd.Append("UnitsInStock,UnitsOnOrder,")
20:    SqlCmd.Append("ProductID FROM Products")
21:   dim sda as new SqlDataAdapter(SqlCmd.ToString(),SqlCon)
22:   dim ds as new DataSet()
23:   sda.Fill(ds,"products")
24:   DLProducts.DataSource = ds.Tables("Products").DefaultView
25:   DLProducts.DataBind()
26:
27: end sub
28:
29: public sub DLProducts_ItemCreated(sender as Object,e as DataListItemEventArgs)
30:
31:  if (e.Item.ItemType = ListItemType.Item or e.Item.ItemType = ListItemType
.AlternatingItem) then
32:   dim iUnitsInStock as integer = integer.Parse(DataBinder.Eval(e.Item.DataItem,
 "UnitsInStock").ToString())
33:   if (iUnitsInStock <= 10) then
34:    CType(e.Item.FindControl("lUnitsOnOrder"), Label).ForeColor = System.Drawing.Color.Red
35:   end if
36:  end if
37:
38: end sub
39:
40: </script>
41: <html>
42:   <body>
43:    <head>
44:
45:     <style rel="stylesheet">
46:      H3 {  font: bold 11pt Verdana, Arial, sans-serif; }
47:      .products {  font: 9pt Verdana, Arial, sans-serif; }
48:      .productsHead {  font: bold 9pt Verdana, Arial, sans-serif;
49:       background-color:Maroon; color:white; }
50:      a {  text-decoration:none; }
51:      a:hover {  text-decoration:underline; color:maroon; }
52:    </style>
53:
54:   </head>
55:     <form runat="server">
56: <center>
57:  <H3>Northwind Inventory Management - VisualBasic.NET</H3>
58: </center>
59: <asp:DataList
60:  id="DLProducts"
61:  runat="server"
62:  Cellpadding="0" Cellspacing="0" Width="750"
63:  BorderWidth="1" Gridlines="Both"
64:  AlternatingItemStyle-BackColor="Tan"
65:  HeaderStyle-CssClass="productsHead"
66:  Font-Size="12"
67:  RepeatColumns="1"
68:  Align="Center"
69:  OnItemCreated="DLProducts_ItemCreated"
70:  >
71:   <ItemTemplate>
72:
73:    <Table cellpadding="4" cellspacing="0" width="100%">
74:     <TR>
75:      <TD ColSpan="2" class="ProductsHead">
76:       <h3><%# DataBinder.Eval(Container.DataItem, "ProductName") %></b>
77:      </TD>
78:     </TR>
79:     <TR>
80:      <TD Width="50%" Align="Left">
81:       <b>Units In Stock</b>
82:      </TD>
83:      <TD Width="50%" Align="Right">
84:       <asp:Label id="lUnitsOnOrder" runat="server"
85:        Text='<%# DataBinder.Eval(Container.DataItem, "UnitsInStock") %>'
86:       />
87:      </TD>
88:     </TR>
89:     <TR>
90:      <TD Width="50%" Align="Left">
91:       <b>Units On Order</b>
92:      </TD>
93:      <TD Width="50%" Align="Right">
94:       <%# DataBinder.Eval(Container.DataItem, "UnitsOnOrder") %>     </TD>
95:     </TR>
96:     <TR>
97:      <TD Width="50%" Align="Left">
98:       <b>Price Per Unit</b>
99:      </TD>
100:      <TD Width="50%" Align="Right">
101:       <%# DataBinder.Eval(Container.DataItem, "UnitPrice", "{ 0:C} ") %>
102:      </TD>
103:     </TR>
104:    </Table>
105:
106:   </ItemTemplate>
107: </asp:DataList>
108:   </form>
109:  </body>
110: </html>
[C#—Replace server code]
01: <%@ import namespace="System.Data" %>
02: <%@ import namespace="System.Data.SqlClient" %>
03: <script language="c#" runat="server">
04:  private string sSqlCon = "server=localhost;uid=sa;pwd=;database=northwind";
05:
06:  public void Page_Load(Object sender, EventArgs e){
07:
08:    if (! IsPostBack){
09:     Bind();
10:    }
11:
12:  }
13:
14: private void Bind() {
15:
16:   SqlConnection SqlCon = new SqlConnection(sSqlCon);
17:   StringBuilder SqlCmd = new StringBuilder();
18:    SqlCmd.Append("SELECT ProductName,UnitPrice,");
19:    SqlCmd.Append("UnitsInStock,UnitsOnOrder,");
20:    SqlCmd.Append("ProductID FROM Products");
21:   SqlDataAdapter sda = new SqlDataAdapter(SqlCmd.ToString(),SqlCon);
22:   DataSet ds = new DataSet();
23:   sda.Fill(ds,"products");
24:   DLProducts.DataSource = ds.Tables["Products"].DefaultView;
25:   DLProducts.DataBind();
26:
27: }
28:
29: public void DLProducts_ItemCreated(Object sender, DataListItemEventArgs e) {
30:
31:  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType
.AlternatingItem) {
32:   int iUnitsInStock = int.Parse(DataBinder.Eval(e.Item.DataItem, "UnitsInStock")
.ToString());
33:   if (iUnitsInStock <= 10) {
34:    ((Label)e.Item.FindControl("lUnitsOnOrder")).ForeColor = System.Drawing.Color.Red;
35:   }
36:  }
37:
38: }
39:
40: </script>

To handle the ItemCreated event using the DataList, first you set the OnItemCreated attribute to be equal to the method that will handle the event. In this case, it's DataList_ItemCreated. The only difference between handling the ItemCreated event in the DataGrid and doing so in the DataList is how you tell the control. Figure 10.5 is an illustration of this page.

Figure 10.5. Using the ItemCreated event to change the ForeColor attribute of the item to red if the value of the UnitsInStock field is less than 10.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.122.244