CSDN博客

img hiyaolee

Use the DataList Control to Present and Edit Data...

发表于2004/10/6 21:56:00  887人阅读


By: John Kilgo Date: January 23, 2003 Download the code. Printer Friendly Version


The DataList is not as powerful as the DataGrid. It requires more work from you since it has no default data presentation format. However, the DataGrid begins to get very cumbersome as the number of columns of data you present increases. Anything more than half a dozen columns or so and you probably induce horizontal scrolling - a real no-no for me. If you put such a DataGrid into edit mode then you really have a horizontal scrolling problem.

The DataList, with its ItemTemplate and EditItemTemplate, make it very easy for you to control the appearance (and screen real estate) of the data. As I said before, it requires more coding but the results may well be worth the effort.

In this article and example program we will deal with the Northwind Customers table. I have included nine columns of editable data. I have divided the work between an aspx page and a code-behind page. In the aspx page we layout our presentation of data, while the code-behind file places the DataList in edit mode, and handles the updating of modified data. The aspx file will be shown below in several sections to make it easier to explain what each section does. This first section is the usual top-of-page "stuff" and the definition of the DataList Control. The only items of note are that we have set the OnEditCommand, OnUpdateCommand, and OnCancelCommand properties to the names of the corresponding event handlers which are defined in the code-behind file.

<%@ Page Language="vb" Src="DataListEdit.aspx.vb" Inherits="Main" %>

<html>
<head>
<title>DataList Edit</title>
<style rel="stylesheet">
  .customers { font: 9pt Verdana, Arial, sans-serif; }
  .customersHead { font: bold 8pt Verdana, Arial, sans-serif;
                  background-color:#4A3C8C; color:white; }
  a { text-decoration:underline; }
  a:hover { text-decoration:underline; color:#4A3C8C; }
</style>
</head>
<body>
<form runat="server" ID="Form1">
<div align="center">
<h3>Customers Table</h3>
</div>
<asp:DataList id="dtlcustomers"
              runat="server"
              width="760"
              BorderWidth="1"
              HeaderStyle-CssClass="customersHead"
              AlternatingItemStyle-BackColor="#DEDFDE"
              Font-Size="10"
              Align="Center"
              OnEditCommand="dtlcustomers_Edit"
              OnUpdateCommand="dtlcustomers_Update"
              OnCancelCommand="dtlcustomers_Cancel">
The following section includes the ItemTemplate for presentation of our data. The code (markup) is fairly long, but all we are doing is creating an html table to present the data. The CompanyName column is shown in a TD element of its own. The rest of the data and column descriptions are show two columns abreast. Notice that we are specifically naming the column headings in one TD element and using the Eval method of the DataBinder class to obtain the actual database table data. We are also using a Button control to induce edit mode in the code-behind file. You can use a LinkButton if you prefer a textual presentation. This may look a little messy at first, but if you run the program (from the link at the bottom of the article) and compare the output to what you see below, I belive you find it very straight forward.
  <ItemTemplate>
    <table cellpadding="2" cellspacing="0" width="100%">
      <tr>
        <td colspan="4" class="customersHead">
          <h3><%# DataBinder.Eval(Container.DataItem, "CompanyName") ></h3>
        </td>
      </tr>
      <tr>
        <td Width="100%" Align="left" colspan="4">
          <asp:button id="btnEdit" Runat="server" CommandName="edit" Text="Edit" />
        </td>
      </tr>
      <tr>
        <td Width="25%" Align="left">
          <b>Contact Name</b>
        </td>
        <td Width="25%" Align="left">
          <%# DataBinder.Eval(Container.DataItem, "ContactName") %>
        </td>
        <td Width="25%" Align="left">
          <b>Contact Title</b>
        </td>
        <td Width="25%" Align="left">
          <%# DataBinder.Eval(Container.DataItem, "ContactTitle") %>
        </td>
      </tr>
      <tr>
        <td Width="25%" Align="left">
          <b>Address</b>
        </td>
        <td Width="25%" Align="left">
          <%# DataBinder.Eval(Container.DataItem, "Address") %>
        </td>
        <td Width="25%" Align="left">
          <b>City</b>
        </td>
        <td width="25%" align="left">
          <%# DataBinder.Eval(Container.DataItem, "City") %>
        </td>
      </tr>
      <tr>
        <td Width="25%" Align="left">
          <b>Postal Code</b>
        </td>
        <td Width="25%" Align="left">
          <%# DataBinder.Eval(Container.DataItem, "PostalCode") %>
        </td>
        <td Width="25%" Align="left">
          <b>Country</b>
        </td>
        <td width="25%" align="left">
          <%# DataBinder.Eval(Container.DataItem, "Country") %>
        </td>
      </tr>
      <tr>
        <td Width="25%" Align="left">
          <b>Phone</b>
        </td>
        <td Width="25%" Align="left">
          <%# DataBinder.Eval(Container.DataItem, "Phone") %>>
        </td>
        <td Width="25%" Align="left">
          <b>Fax</b>
        </td>
        <td width="25%" align="left">
          <%# DataBinder.Eval(Container.DataItem, "Fax") %>
        </td>
      </tr>
    </Table>
  </ItemTemplate>
Next we must decide how our data and column descriptions are to appear while in edit mode. That is the purpose of the markup below following the EditItemTemplate tag. The process is much the same as in the ItemTemplate section above. The main difference is that we are creating TextBox controls to contain the actual data, so that the data becomes editable. I also chose to present the column descriptions and data one abreast rather than two abreast as above. I did this for two reasons. One was just to show that the ItemTemplate and EditItemTemplates stand alone and do not have to have the same presentation format, and to make more room for several of the TextBoxes that can hold 30 - 40 characters of data. Again, once you run the program you will see the difference in presentation.
  <EditItemTemplate>
    <table cellpadding="2" cellspacing="0" width="100%">
      <tr>
        <td colspan="2" class="customersHead">
          <h3><%# DataBinder.Eval(Container.DataItem, "CompanyName") %></h3>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>Company Name</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtCompanyName" runat="server" MaxLength="40" Columns="40"
          Text='<%# DataBinder.Eval(Container.DataItem, "CompanyName") %>'/>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>Contact Name</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtContactName" Runat="server" MaxLength="30" Columns="30"
          Text='<%# DataBinder.Eval(Container.DataItem, "ContactName") %>'/>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>Contact Title</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtContactTitle" Runat="server" MaxLength="30" Columns="30"
          Text='<%# DataBinder.Eval(Container.DataItem, "ContactTitle") %>'/>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>Address</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtAddress" Runat="server" MaxLength="60" Columns="60"
          Text='<%# DataBinder.Eval(Container.DataItem, "Address") %>'/>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>City</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtCity" Runat="server" MaxLength="15" Columns="15"
          Text='<%# DataBinder.Eval(Container.DataItem, "City") %>'/>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>Postal Code</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtPostalCode" Runat="server" MaxLength="10" Columns="10"
          Text='<%# DataBinder.Eval(Container.DataItem, "PostalCode") %>'/>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>Country</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtCountry" Runat="server" MaxLength="15" Columns="15"
          Text='<%# DataBinder.Eval(Container.DataItem, "Country") %>'/>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>Phone</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtPhone" Runat="server" MaxLength="24" Columns="24"
          Text='<%# DataBinder.Eval(Container.DataItem, "Phone") %>'/>
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="Left">
          <b>Fax</b>
        </td>
        <td Width="50%" Align="left">
          <asp:TextBox id="txtFax" Runat="server" MaxLength="24" Columns="24"
          Text='<%# DataBinder.Eval(Container.DataItem, "Fax") %>'/>
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:Label id="lblCustomerID" runat="server"
          Text='<%# DataBinder.Eval(Container.DataItem, "CustomerID") %>'
          Visible="false" />
        </td>
      </tr>
      <tr>
        <td Width="50%" Align="right">
          <asp:Button id="btnUpdate" Runat="server" CommandName="update" Text="Update" />
          <asp:Button id="btnCancel" Runat="server" CommandName="cancel" Text="Cancel" />
        </td>
        <td Width="50%" Align="Left">
           
        </td>
      </tr>
    </table>
  </EditItemTemplate>
</asp:DataList>
</form>
</body>
</html>
Now for the code-behind file. We will also present this file in sections to better illustrate and explain the code. First are the Page_Load and BindTheData() subroutines. The Page_Load simply checks to make sure this is the first time the page has been loaded and calls the BindTheData subroutine. BindTheData uses a DataAdapter to obtain the data from the table, fills a DataSet and binds the data to the DataList control (dtlCustomers).
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Configuration

Public Class Main : Inherits Page

  Private strConn As String = ConfigurationSettings.AppSettings("ConnectionString")
  Public dtlCustomers As DataList

  Public Sub Page_Load(sender as Object, e as EventArgs)

    If Not IsPostBack Then
      BindTheData()
    End If

  End Sub

  Private Sub BindTheData()

    Dim objConn as new SqlConnection(strConn)
    Dim strSQL as String
    strSQL = "SELECT Top 5 * FROM Customers"
    Dim sda as new SqlDataAdapter(strSQL, objConn)
    Dim ds as new DataSet()
    sda.Fill(ds,"Customers")
    dtlCustomers.DataSource = ds.Tables("Customers").DefaultView
    dtlCustomers.DataBind()

  End Sub
Next are two short bits of code to handle the dtlCustomers_Edit and dtlCustomers_Cancel subroutines. Remember in the aspx file above we set several properties of the Datalist control to call events in the code-behind file. Edit and Cancel were two of those. We set the OnEditCommand property equal to "dtlcustomers_Edit". We also created a button with a CommandName of "edit". The combination of the two brings us to the edit subroutine presented below. We use the ItemIndex property to know which row is to be edited. We also created a Cancel button (and set the OnCancelCommand property) to get us out of edit mode if we want to abandon changes rather than going ahead with the update of the row. Cancel is handled easily simply by setting the EditItemIndex property to -1.
  Public Sub dtlCustomers_Edit(sender as Object, e as DataListCommandEventArgs)

    dtlCustomers.EditItemIndex = e.Item.ItemIndex
    BindTheData()

  End Sub

  Public Sub dtlCustomers_Cancel(sender as Object, e as DataListCommandEventArgs)

    dtlCustomers.EditItemIndex = -1
    BindTheData()

  End Sub
The last section of code presented is the dtlCustomers_Update subroutine and is by far the longest section. As you may recall in the aspx page EditItemTemplate we created TextBoxes to present data for editing. The value in those TextBox controls are used to change the data. The values of the textboxes are gathered and placed in string variables in the code immediately below using the FindControl method. We now have the data after any editing that took place. Immediately below that is our update statement which is constructed using parameters for the column values. Below that we Add parameters to the sqlCommand object and set the parameter values to the string variables holding our edited data. Following that we simply do the update and then rebind the DataList control.
  Public Sub dtlCustomers_Update(sender As Object, e As DataListCommandEventArgs)

    Dim strCompanyName, strContactName, strContactTitle, strCustomerID As String
    Dim strAddress, strCity, strPostalCode, strCountry, strPhone, strFax As String

    strCompanyName = CType(e.Item.FindControl("txtCompanyName"), TextBox).Text
    strContactName = CType(e.Item.FindControl("txtContactName"), TextBox).Text
    strContactTitle = CType(e.Item.FindControl("txtContactTitle"), TextBox).Text
    strAddress = CType(e.Item.FindControl("txtAddress"), TextBox).Text
    strCity = CType(e.Item.FindControl("txtCity"), TextBox).Text
    strPostalCode = CType(e.Item.FindControl("txtPostalCode"),TextBox).Text
    strCountry = CType(e.Item.FindControl("txtCountry"),TextBox).Text
    strPhone = CType(e.Item.FindControl("txtPhone"),TextBox).Text
    strFax = CType(e.Item.FindControl("txtFax"),TextBox).Text
    strCustomerID = CType(e.Item.FindControl("lblCustomerID"), Label).Text

    Dim strSQL As String
    strSQL = "Update Customers " _
    & "Set CompanyName = @CompanyName," _
    & "ContactName = @ContactName," _
    & "ContactTitle = @ContactTitle, " _
    & "Address = @Address, " _
    & "City = @City, " _
    & "PostalCode = @PostalCode, " _
    & "Country = @Country, " _
    & "Phone = @Phone, " _
    & "Fax = @Fax " _
    & "WHERE CustomerID = @CustomerID"

    Dim objConn As New SqlConnection(strConn)
    Dim cmdSQL As New SqlCommand(strSQL, objConn)
    cmdSQL.Parameters.Add(new SqlParameter("@CompanyName", SqlDbType.NVarChar, 40))
    cmdSQL.Parameters("@CompanyName").Value = strCompanyName
    cmdSQL.Parameters.Add(new SqlParameter("@ContactName", SqlDbType.NVarChar, 30))
    cmdSQL.Parameters("@ContactName").Value = strContactName
    cmdSQL.Parameters.Add(new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30))
    cmdSQL.Parameters("@ContactTitle").Value = strContactTitle
    cmdSQL.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 60))
    cmdSQL.Parameters("@Address").Value = strAddress
    cmdSQL.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 15))
    cmdSQL.Parameters("@City").Value = strCity
    cmdSQL.Parameters.Add(new SqlParameter("@PostalCode", SqlDbType.NVarChar, 10))
    cmdSQL.Parameters("@PostalCode").Value = strPostalCode
    cmdSQL.Parameters.Add(new SqlParameter("@Country", SqlDbType.NVarChar, 15))
    cmdSQL.Parameters("@Country").Value = strCountry
    cmdSQL.Parameters.Add(new SqlParameter("@Phone", SqlDbType.NVarChar, 24))
    cmdSQL.Parameters("@Phone").Value = strPhone
    cmdSQL.Parameters.Add(new SqlParameter("@Fax", SqlDbType.NVarChar, 24))
    cmdSQL.Parameters("@Fax").Value = strFax
    cmdSQL.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.NChar, 5))
    cmdSQL.Parameters("@CustomerID").Value = strCustomerID

    objConn.Open()
    cmdSQL.ExecuteNonQuery()
    objConn.Close()

    dtlCustomers.EditItemIndex = -1
    BindTheData()

  End Sub

End Class
Conclusion: You have seen a lot coding necessary to presenting a DataList, placing it in edit mode, and then canceling or updating the data after making changes. If you take the code one section at a time and see what each section actually does, I believe you will find that you can finely tune how your data is presented both for viewing and for editing, and how to accomplish the update. Best of luck!

You may run the code here.
You may download the code here.

阅读全文
0 0

相关文章推荐

img
取 消
img