Enabling Editing Using the DataList

DataList"-->

only for RuBoard

Enabling Editing Using the DataList

Using the DataList control rather than the DataGrid gives you significantly more control over the layout of the rendered page. For example, since the DataList doesn't have a default look, you can have one look for items while in edit mode and another for those that are not. Listing 10.3 uses the DataList with editing enabled. After this listing, we'll dissect the code used for editing to show you exactly what's going on.

Listing 10.3 Enabling Editing in 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_Edit(sender as Object, e as DataListCommandEventArgs) 30: 31:  DLProducts.EditItemIndex = e.Item.ItemIndex 32:  Bind() 33: 34: end sub 35: 36: public sub DLProducts_Cancel(sender as Object, e as DataListCommandEventArgs) 37: 38:  DLProducts.EditItemIndex = -1 39:  Bind() 40: 41: end sub 42: 43: public sub DLProducts_Update(sender as Object, e as DataListCommandEventArgs) 44: 45:  dim sProductName,sUnitsInStock,sUnitsOnOrder,sProductID as string 46:   sProductName = CType(e.Item.FindControl("tProductName"), TextBox).Text 47:   sUnitsInStock = CType(e.Item.FindControl("tUnitsInStock"), TextBox).Text 48:   sUnitsOnOrder = CType(e.Item.FindControl("tUnitsOnOrder"), TextBox).Text 49:   sProductID = CType(e.Item.FindControl("lProductID"), Label).Text 50: 51:  dim sSqlCmd as new StringBuilder() 52:   sSqlCmd.Append("UPDATE Products ") 53:   sSqlCmd.Append("SET ProductName = @ProductName,") 54:   sSqlCmd.Append("UnitsInStock = @UnitsInStock,") 55:   sSqlCmd.Append("UnitsOnOrder = @UnitsOnOrder ") 56:   sSqlCmd.Append("WHERE ProductID = @ProductID") 57: 58:  dim SqlCon as new SqlConnection(sSqlCon) 59:  Dim SqlCmd as new SqlCommand(sSqlCmd.ToString(),SqlCon) 60:   SqlCmd.Parameters.Add(new SqlParameter("@ProductName", SqlDbType.NVarChar, 40)) 61:   SqlCmd.Parameters("@ProductName").Value = sProductName 62:   SqlCmd.Parameters.Add(new SqlParameter("@UnitsInStock", SqlDbType.SmallInt)) 63:   SqlCmd.Parameters("@UnitsInStock").Value = sUnitsInStock 64:   SqlCmd.Parameters.Add(new SqlParameter("@UnitsOnOrder", SqlDbType.SmallInt)) 65:   SqlCmd.Parameters("@UnitsOnOrder").Value = sUnitsOnOrder 66:   SqlCmd.Parameters.Add(new SqlParameter("@ProductID", SqlDbType.SmallInt)) 67:   SqlCmd.Parameters("@ProductID").Value = sProductID 68: 69:  SqlCon.Open() 70:  SqlCmd.ExecuteNonQuery() 71:  SqlCon.Close() 72: 73:  DLProducts.EditItemIndex = -1 74:  Bind() 75: 76: end sub 77: 78: </script> 79: <html> 80:   <body> 81:    <head> 82: 83:     <style rel="stylesheet"> 84:      H3 {  font: bold 11pt Verdana, Arial, sans-serif; } 85:      .products {  font: 9pt Verdana, Arial, sans-serif; } 86:      .productsHead {  font: bold 9pt Verdana, Arial, sans-serif; 87:       background-color:Maroon; color:white; } 88:      a {  text-decoration:none; } 89:      a:hover {  text-decoration:underline; color:maroon; } 90:    </style> 91: 92:   </head> 93:     <form runat="server"> 94: <center> 95:  <H3>Northwind Inventory Management - VisualBasic.NET</H3> 96: </center> 97: <asp:DataList 98:  id="DLProducts" 99:  runat="server" 100:  Cellpadding="0" Cellspacing="0" Width="750" 101:  BorderWidth="1" Gridlines="Both" 102:  AlternatingItemStyle-BackColor="Tan" 103:  HeaderStyle-CssClass="productsHead" 104:  Font-Size="12" 105:  RepeatColumns="1" 106:  Align="Center" 107:  OnCancelCommand="DLProducts_Cancel" 108:  OnEditCommand="DLProducts_Edit" 109:  OnUpdateCommand="DLProducts_Update" 110: 111:  > 112:   <ItemTemplate> 113: 114:    <Table cellpadding="4" cellspacing="0" width="100%"> 115:     <TR> 116:      <TD ColSpan="2" class="ProductsHead"> 117:       <h3><%# DataBinder.Eval(Container.DataItem, "ProductName") %></b> 118:      </TD> 119:     </TR> 120:     <TR> 121:      <TD Width="50%" Align="Left"> 122:       <b>Units In Stock</b> 123:      </TD> 124:      <TD Width="50%" Align="Right"> 125:       <%# DataBinder.Eval(Container.DataItem, "UnitsInStock") %> 126:      </TD> 127:     </TR> 128:     <TR> 129:      <TD Width="50%" Align="Left"> 130:       <b>Units On Order</b> 131:      </TD> 132:      <TD Width="50%" Align="Right"> 133:       <%# DataBinder.Eval(Container.DataItem, "UnitsOnOrder") %> 134:      </TD> 135:     </TR> 136:     <TR> 137:      <TD Width="50%" Align="Left"> 138:       <b>Price Per Unit</b> 139:      </TD> 140:      <TD Width="50%" Align="Right"> 141:       <%# DataBinder.Eval(Container.DataItem, "UnitPrice", "{ 0:C} ") %> 142:      </TD> 143:     </TR> 144:     <TR> 145:      <TD Width="50%" Align="Left"> 146:       <b>Edit This Item</b> 147:      </TD> 148:      <TD Width="50%" Align="Right"> 149:       <asp:LinkButton Runat="server" CommandName="edit" Text="Edit" /> 150:      </TD> 151:     </TR> 152:    </Table> 153: 154:   </ItemTemplate> 155: 156:   <EditItemTemplate> 157: 158:    <Table cellpadding="4" cellspacing="0" width="100%"> 159:     <TR> 160:      <TD ColSpan="2" class="ProductsHead"> 161:       <h3><%# DataBinder.Eval(Container.DataItem, "ProductName") %></b> 162:      </TD> 163:     </TR> 164:     <TR> 165:      <TD Width="50%" Align="Left"> 166:       <b>Product Name</b> 167:      </TD> 168:      <TD Width="50%" Align="Right"> 169:       <asp:TextBox id="tProductName" runat="server" 170:        Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>' 171:        /> 172:      </TD> 173:     </TR> 174:     <TR> 175:      <TD Width="50%" Align="Left"> 176:       <b>Units In Stock</b> 177:      </TD> 178:      <TD Width="50%" Align="Right"> 179:       <asp:TextBox id="tUnitsInStock" Runat="server" 180:        Text='<%# DataBinder.Eval(Container.DataItem, "UnitsInStock") %>' 181:        /> 182:      </TD> 183:     </TR> 184:     <TR> 185:      <TD Width="50%" Align="Left"> 186:       <b>Units On Order</b> 187:      </TD> 188:      <TD Width="50%" Align="Right"> 189:       <asp:TextBox id="tUnitsOnOrder" Runat="server" 190:        Text='<%# DataBinder.Eval(Container.DataItem, "UnitsOnOrder") %>' 191:        /> 192:      </TD> 193:     </TR> 194:     <TR> 195:      <TD ColSpan="2"> 196:       <asp:Label id="lProductID" runat="server" 197:        Text='<%# DataBinder.Eval(Container.DataItem, "ProductID") %>' 198:        Visible="false" 199:        /> 200:      </TD> 201:     </TR> 201:     <TR> 202:      <TD Width="50%" Align="Left"> 203:       <b>Edit This Item</b> 204:      </TD> 205:      <TD Width="50%" Align="Right"> 206:       <asp:LinkButton Runat="server" CommandName="update" Text="Update" /> 207:       <asp:LinkButton Runat="server" CommandName="cancel" Text="Cancel" /> 208:      </TD> 209:     </TR> 210:    </Table> 211: 212:   </EditItemTemplate> 213: 214: </asp:DataList> 215:   </form> 216:  </body> 217: </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_Edit(Object sender, DataListCommandEventArgs e) { 30: 31:  DLProducts.EditItemIndex = e.Item.ItemIndex; 32:  Bind(); 33: 34: } 35: 36: public void DLProducts_Cancel(Object sender, DataListCommandEventArgs e) { 37: 38:  DLProducts.EditItemIndex = -1; 39:  Bind(); 40: 41: } 42: 43: public void DLProducts_Update(Object sender, DataListCommandEventArgs e) { 44: 45:  string sProductName,sUnitsInStock,sUnitsOnOrder,sProductID; 46:   sProductName = ((TextBox)e.Item.FindControl("tProductName")).Text; 47:   sUnitsInStock = ((TextBox)e.Item.FindControl("tUnitsInStock")).Text; 48:   sUnitsOnOrder = ((TextBox)e.Item.FindControl("tUnitsOnOrder")).Text; 49:   sProductID = ((Label)e.Item.FindControl("lProductID")).Text; 50: 51:  StringBuilder sSqlCmd = new StringBuilder(); 52:   sSqlCmd.Append("UPDATE Products "); 53:   sSqlCmd.Append("SET ProductName = @ProductName,"); 54:   sSqlCmd.Append("UnitsInStock = @UnitsInStock,"); 55:   sSqlCmd.Append("UnitsOnOrder = @UnitsOnOrder "); 56:   sSqlCmd.Append("WHERE ProductID = @ProductID"); 57: 58:  SqlConnection SqlCon = new SqlConnection(sSqlCon); 59:  SqlCommand SqlCmd = new SqlCommand(sSqlCmd.ToString(),SqlCon); 60:   SqlCmd.Parameters.Add(new SqlParameter("@ProductName", SqlDbType.NVarChar, 40)); 61:   SqlCmd.Parameters["@ProductName"].Value = sProductName; 62:   SqlCmd.Parameters.Add(new SqlParameter("@UnitsInStock", SqlDbType.SmallInt)); 63:   SqlCmd.Parameters["@UnitsInStock"].Value = sUnitsInStock; 64:   SqlCmd.Parameters.Add(new SqlParameter("@UnitsOnOrder", SqlDbType.SmallInt)); 65:   SqlCmd.Parameters["@UnitsOnOrder"].Value = sUnitsOnOrder; 66:   SqlCmd.Parameters.Add(new SqlParameter("@ProductID", SqlDbType.SmallInt)); 67:   SqlCmd.Parameters["@ProductID"].Value = sProductID; 68: 69:  SqlCon.Open(); 70:  SqlCmd.ExecuteNonQuery(); 71:  SqlCon.Close(); 72: 73:  DLProducts.EditItemIndex = -1; 74:  Bind(); 75: 76: } 77: 78: </script> 

We will go over Listing 10.3 in detail in the following three sections. The first section, "Putting the DataList into Edit Mode ," explains how to configure the DataList to support editing. The next section, "Updating Data with the DataList ," explains how to update your database with the edited data. Finally, "Cancelling out of Edit Mode," explains how to cancel out of edit mode without saving the edited data back to the database.

Putting the DataList into Edit Mode

Looking at Listing 10.3 you'll notice that editing using DataList is a little different than with the DataGrid . The first thing you probably noticed is that there isn't an EditCommandColumn . Instead you have to use button controls to raise the CancelCommand , UpdateCommand , and EditCommand events. You might also have noticed that you have to manually create the user interface for both normal and edit mode by use of templates.

First, let's take a look at the structure of the DataList itself. There are two templates used in Listing 10.3: the ItemTemplate (lines 112 “154), which as you remember is rendered once for each row in the data source, and the EditItemTemplate (lines 156 “213), which is rendered only when the DataList is in edit mode. It will only be used for the item that has been chosen by the user to edit. You can use similar HTML code as you do in the ItemTemplate or you can use completely different HTML code. Whether or not you decide to use a similar html structure within the EditItemTemplate you have to decide what controls you are going to use to allow the user to edit data such as a TextBox control or a DropDownList control. In Listing 10.3 we use TextBox controls.

As previously mentioned, you need to use Button controls to raise the EditCommand event. On line 149 you will find the LinkButton we use to enter into edit mode in Listing 10.3. The CommandName attribute of the Button control is how you control which event is raised when using the DataList control. As with the DataGrid , the DataList has 4 different events that you will use when dealing with editing data. Each event is raised by using a key word as the CommandName attribute value of the button control and by setting its correlating method's value ( OnEditCommand ) equal to event which will handle the command ( EditCommand ). Table 10.1 contains each.

Table 10.1. The button ColumnName attribute signals the DataList method to raise the correlating DataList event.
DataList Method Event Button or LinkButton DataList CommandName
EditCommand OnEditCommand edit
DeleteCommand OnDeleteCommand delete
CancelCommand OnCancelCommand cancel
DeleteCommand OnDeleteCommand delete

Once the LinkButton is clicked and the EditCommand event is handled by DLProducts_Edit (lines 29 “34) that item is put into edit mode exactly as you would using the DataGrid . First, you set the DataList 's EditItemIndex attribute equal to the selected item's ItemIndex . You retrieve the ItemIndex through the Item property of the DataListCommandEventArgs parameter. The DataListCommandEventArgs contains and behaves similar to the DataGrid 's DataGridCommandEventArgs . After setting the EditItemIndex you want to rebind the DataList to its data source (i.e. Bind method). Figure 10.3 shows this DataList in edit mode.

Figure 10.3. This DataList in edit mode.
graphics/10fig03.gif

Updating Data with the DataList

Now that you have the basics of how to handle editing events with the DataList the rest is easy. You will see the UpdateCommand behaves nearly the same way as the DataGrid with two differences. The first difference is how you raise the EditCommand event. The event is handled by the DLProducts_Update method found on lines 43 “76 and is raised by the LinkButton control on line 207 ”notice the CommandName for the button is update . The second difference is the way you retrieve the edited values from their perspective controls. This is because the DataList has no default structure so you cannot depend on the Cells and Controls collection to retrieve the values. Instead you use the Control classes FindControl method.

The FindControl method expects the ID attribute as a parameter and will search the naming container for that attribute and will return a Control object. Because the return is a Control you must cast or convert this Control object to the original control. In Listing 10.3, you need the values from four different controls: three TextBox controls and one Label control. This is shown in the following code and on lines 45 “49 from Listing 10.3:

 [Visual Basic] dim sProductName,sUnitsInStock,sUnitsOnOrder,sProductID as string   sProductName = CType(e.Item.FindControl("tProductName"), TextBox).Text   sUnitsInStock = CType(e.Item.FindControl("tUnitsInStock"), TextBox).Text   sUnitsOnOrder = CType(e.Item.FindControl("tUnitsOnOrder"), TextBox).Text   sProductID = CType(e.Item.FindControl("lProductID"), Label).Text [C#] string sProductName,sUnitsInStock,sUnitsOnOrder,sProductID;   sProductName = ((TextBox)e.Item.FindControl("tProductName")).Text;   sUnitsInStock = ((TextBox)e.Item.FindControl("tUnitsInStock")).Text;   sUnitsOnOrder = ((TextBox)e.Item.FindControl("tUnitsOnOrder")).Text;   sProductID = ((Label)e.Item.FindControl("lProductID")).Text; 

First I create four string variables and then I retrieve each of the four controls Text attribute values. The rest of the code is exactly the same as the code in the DataGrid 's update method. You construct your SQL statement, insert the data, take the DataList out of edit mode, and rebind the DataList to its data source.

Cancelling Out of Edit Mode

Cancelling out of edit mode is done in the CancelCommand event. In our example this is handled by the DLProducts_Cancel method (lines 36 “41) which is raised by the LinkButton control on line 208 (the CommandName for this LinkButton is cancel ). It's just a matter of setting the DataList's EditItemIndex attribute to -1 .

only for RuBoard


Programming Data-Driven Web Applications with ASP. NET
Programming Data-Driven Web Applications with ASP.NET
ISBN: 0672321068
EAN: 2147483647
Year: 2000
Pages: 170

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net