【小题大做】 Magic Page (2) : Refactoring

下面是对上贴里的编码的初浅的重构,

  1. AuthorList.aspx:

<%@ Page Language=”C#” AutoEventWireup=”false” CodeBehind=”AuthorList.aspx.cs” Inherits=”JoyCode.AuthorListPage” %>
<html>
<head>
</head>
<body style=”font: 10pt verdana”>

  <form id=”Form1″ runat=”server”>

    <h3><font face=”Verdana”>Updating a Row of Data w/ Validation</font></h3>

    <span id=”Message” EnableViewState=”false” style=”font: arial 11pt;” runat=”server”/><p>

    <ASP:DataGrid id=”MyDataGrid” runat=”server”
      Width=”800″
      BackColor=”#ccccff”
      BorderColor=”black”
      ShowFooter=”false”
      CellPadding=3
      CellSpacing=”0″
      Font-Name=”Verdana”
      Font-Size=”8pt”
      HeaderStyle-BackColor=”#aaaadd”
    >

      <Columns>
        <asp:EditCommandColumn EditText=”Edit” CancelText=”Cancel” UpdateText=”Update”  ItemStyle-Wrap=”false”/>
        <asp:BoundColumn HeaderText=”au_id” SortExpression=”au_id” ReadOnly=”True” DataField=”au_id” ItemStyle-Wrap=”false”/>
        <asp:TemplateColumn HeaderText=”au_lname” SortExpression=”au_lname”>
          <ItemTemplate>
            <asp:Label ID=”Label1″ runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “au_lname”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <nobr>
            <asp:TextBox runat=”server” id=”edit_LName” Text='<%# DataBinder.Eval(Container.DataItem, “au_lname”) %>’/>
            <asp:RequiredFieldValidator id=”au_lnameReqVal”
                ControlToValidate=”edit_LName”
                Display=”Dynamic”
                Font-Name=”Verdana” Font-Size=”12″
                runat=server>
                    &nbsp;
            </asp:RequiredFieldValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”au_fname” SortExpression=”au_fname”>
          <ItemTemplate>
            <asp:Label ID=”Label2″ runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “au_fname”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <nobr>
            <asp:TextBox runat=”server” id=”edit_FName” Text='<%# DataBinder.Eval(Container.DataItem, “au_fname”) %>’/>
            <asp:RequiredFieldValidator id=”au_fnameReqVal”
                ControlToValidate=”edit_FName”
                Display=”Dynamic”
                Font-Name=”Verdana” Font-Size=”12″
                runat=server>
                    &nbsp;

            </asp:RequiredFieldValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”phone” SortExpression=”phone”>
          <ItemTemplate>
            <asp:Label ID=”Label3″ runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “phone”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <nobr>
            <asp:TextBox runat=”server” id=”edit_Phone” Text='<%# DataBinder.Eval(Container.DataItem, “phone”) %>’/>
            <asp:RequiredFieldValidator id=”phoneReqVal”
                ControlToValidate=”edit_Phone”
                Display=”Dynamic”
                Font-Name=”Verdana” Font-Size=”12″
                runat=server>
                    &nbsp;*
            </asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator id=”phoneRegexVal”
                ControlToValidate=”edit_Phone”
                ValidationExpression=”[0-9]{3} [0-9]{3}-[0-9]{4}”
                Display=”Dynamic”
                Font-Name=”Arial” Font-Size=”11″
                runat=server>
                    * Phone must be in form: XXX XXX-XXXX <br>
            </asp:RegularExpressionValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”address” SortExpression=”address”>
          <ItemTemplate>
            <asp:Label ID=”Label4″ runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “address”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat=”server” id=”edit_Address” Text='<%# DataBinder.Eval(Container.DataItem, “address”) %>’/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”city” SortExpression=”city”>
          <ItemTemplate>
            <asp:Label ID=”Label5″ runat=”server” Text='<%# DataBinder.Eval(Conta
iner.DataItem, “city”) %>’/>
          </ItemTemplate>
   &n
bsp;      <EditItemTemplate>
            <asp:TextBox runat=”server” id=”edit_City” Text='<%# DataBinder.Eval(Container.DataItem, “city”) %>’/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”state” SortExpression=”state”>
          <ItemTemplate>
            <asp:Label ID=”Label6″ runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “state”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:DropDownList runat=”server” id=”edit_State”>
                  <asp:ListItem>CA</asp:ListItem>
                  <asp:ListItem>IN</asp:ListItem>
                  <asp:ListItem>KS</asp:ListItem>
                  <asp:ListItem>MD</asp:ListItem>
                  <asp:ListItem>MI</asp:ListItem>
                  <asp:ListItem>OR</asp:ListItem>
                  <asp:ListItem>TN</asp:ListItem>
                  <asp:ListItem>UT</asp:ListItem>
            </asp:DropDownList>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”zip” SortExpression=”zip”>
          <ItemTemplate>
            <asp:Label ID=”Label7″ runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “zip”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat=”server” id=”edit_Zip” Text='<%# DataBinder.Eval(Container.DataItem, “zip”) %>’/>
            <asp:RegularExpressionValidator id=”RegularExpressionValidator1″
                ASPClass=”RegularExpressionValidator” ControlToValidate=”edit_Zip”
                ValidationExpression=”[0-9]{5}”
                Display=”Dynamic”
                Font-Name=”Arial” Font-Size=”11″
                runat=server>
                    * Zip Code must be 5 numeric digits <br>
            </asp:RegularExpressionValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”contract” SortExpression=”contract”>
          <ItemTemplate>
            <asp:Label ID=”Label8″ runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “contract”, “{0}”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:CheckBox runat=”server” id=”edit_Contract” Checked='<%# DataBinder.Eval(Container.DataItem, “contract”)

%>’/>
          </EditItemTemplate>
        </asp:TemplateColumn>
      </Columns>

    </ASP:DataGrid>

  </form>

</body>
</html>

  1. AuthorList.aspx.cs:

using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using JoyCode;

namespace JoyCode
{

    public class AuthorListPage : System.Web.UI.Page
    {
        AuthorManager am;

 protected HtmlGenericControl Message;
      protected DataGrid MyDataGrid;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.Load += new EventHandler(Page_Load);
            this.MyDataGrid.EditCommand += new DataGridCommandEventHandler(MyDataGrid_Edit);
            this.MyDataGrid.UpdateCommand += new DataGridCommandEventHandler(MyDataGrid_Update);
            this.MyDataGrid.CancelCommand += new DataGridCommandEventHandler(MyDataGrid_Cancel);
            this.MyDataGrid.ItemDataBound += new DataGridItemEventHandler(MyDataGrid_ItemDataBound);

            this.MyDataGrid.AutoGenerateColumns = false;
            this.MyDataGrid.DataKeyField = “au_id”;

            am = new AuthorManager();

        }
        protected void Page_Load(Object Src, EventArgs E)
        {
         
            if (!IsPostBack)
                BindGrid();

        }

        public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
        {
            MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
            BindGrid();
        }

        public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
        {
            MyDataGrid.EditItemIndex = -1;
            BindGrid();
        }

        public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
        {
            if (Page.IsValid)
            {
                string id = MyDataGrid.DataKeys[(int)E.Item.ItemIndex].ToString();

                String[] cols = { “LName”, “FName”, “Phone”, “Address”, “City”, “Zip” };
                String[] vals = new String[cols.Length];

                for (int i = 0; i < cols.Length; i++)
                {
                    String colvalue = ((TextBox)E.Item.FindControl(“edit_” + cols[i])).Text;
                    vals[i] = colvalue;
                }

                string lname = vals[0];
                string fname = vals[1];
                string phone = vals[2];
                string address = vals[3];
                string city = vals[4];
                string zip = vals[5];

                string state = ((DropDownList)E.Item.FindControl(“edit_State”)).SelectedItem.ToString();

                bool contract = ((CheckBox)E.Item.FindControl(“edit_Contract”)).Checked;

                try
                {
                    am.UpdateAuthor(id, lname, fname, phone, address, city, state, zip, contract);
                    Message.InnerHtml = “<b>Record Updated</b><br>”;
                    MyDataGrid.EditItemIndex = -1;
                }
                catch (RecordExistException ex)
                {
                   
                   Message.InnerHtml = “ERROR: ” + ex.Message;
                    Message.Style[“color”] = “red”;
                }
                catch(UnknownException ex)
                {
                    Message.InnerHtml = “ERROR: Could not update record, please ensure the fields are correctly filled out”;
                    Message.Style[“color”] = “red”;
                }

                BindGrid();
            }
            else
            {
                Message.InnerHtml = “ERROR: Please check each field for error conditions.”;
                Message.Style[“color”] = “red”;
            }
        }

        private void MyDataGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.EditItem)
            {
                for (int i = 0; i < e.Item.Controls.Count; i++)
                {
                    try
                    {
                        if (e.Item.Controls[i].Controls[1]  is TextBox)
                        {
                            TextBox tb = (TextBox)e.Item.Controls[i].Controls[1];
                            tb.Text = Server.HtmlDecode(tb.Text);//这里是否算?
                        }
                        else if (e.Item.Controls[i].Controls[1]  is DropDownList)
                        {
                            DropDownList ddl = e.Item.Controls[i].Controls[1] as DropDownList;
                            string state = (String)((DataRowView)e.Item.DataItem)[“state”];
                            ListItem li = ddl.Items.FindByText(state);
                            if (li != null)
                            {
                                   ddl.SelectedIndex = ddl.Items.IndexOf(li);
                            }

                        }

                    }
                    catch
                    {

                    }
                }
            }
        }

        public void BindGrid()
        {
           
            MyDataGrid.DataSource = am.GetAuthors();
            MyDataGrid.DataBind();
        }

    }
}

  1. Author.cs:

using System;
using System.Data;
using System.Web;
using System.Runtime.Serialization;
using System.Data.SqlClient;

namespace JoyCode
{

    public class UnknownException : ApplicationException
    {
        public UnknownException() {}
        public UnknownException(string message) : base(message) {}
        protected UnknownException(SerializationInfo info, StreamingContext context) : base(info,context) {}
        public UnknownException(string message, Exception innerException) : base(message, innerException) {}

    }

    public class RecordExistException : ApplicationException
    {
        public RecordExistException() { }
        public RecordExistException(string message) : base(message) { }
        protected RecordExistException(SerializationInfo info, StreamingContext context) : base(info, context) { }
        public RecordExistException(string message, Exception innerException) : base(message, innerException) { }

    }

    public class AuthorManager
    {
        SqlConnection myConnection;
        public AuthorManager()
        {
            myConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings[“ConnectionString”]);
        }

        public DataView GetAuthors()
        {
            SqlDataAdapter myCommand = new SqlDataAdapter(“select * from Authors”, myConnection);

            DataSet ds = new DataSet();
            myCommand.Fill(ds, “Authors”);
            return ds.Tables[“Authors”].DefaultView;

        }

        public void UpdateAuthor(string id, string lname, string fname, string phone, string address, string city, string

state, string zip, bool contract)
        {
            String updateCmd = “UPDATE Authors SET au_id = @Id, au_lname = @LName, au_fname = @FName, phone = @Phone, “
        + “address = @Address, city = @City, state = @State, zip = @Zip, contract = @Contract where au_id = @Id”;

            SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);

            myCommand.Parameters.Add(new SqlParameter(“@Id”, SqlDbType.NVarChar, 11)).Value = id;
            myCommand.Parameters.Add(new SqlParameter(“@LName”, SqlDbType.NVarChar, 40)).Value =

HttpUtility.HtmlEncode(lname);
            myCommand.Parameters.Add(new SqlParameter(“@FName”, SqlDbType.NVarChar, 20)).Value =

HttpUtility.HtmlEncode(fname);
            myCommand.Parameters.Add(new SqlParameter(“@Phone”, SqlDbType.NChar, 12)).Value = HttpUtility.HtmlEncode(phone);
            myCommand.Parameters.Add(new SqlParameter(“@Address”, SqlDbType.NVarChar, 40)).Value =

HttpUtility.HtmlEncode(address);
            myCommand.Parameters.Add(new SqlParameter(“@City”, SqlDbType.NVarChar, 20)).Value = HttpUtility.HtmlEncode(city);
            myCommand.Parameters.Add(new SqlParameter(“@State”, SqlDbType.NChar, 2)).Value = HttpUtility.HtmlEncode(state);
            myCommand.Parameters.Add(new SqlParameter(“@Zip”, SqlDbType.NChar, 5)).Value = HttpUtility.HtmlEncode(zip);
            myCommand.Parameters.Add(new SqlParameter(“@Contract”, SqlDbType.Int)).Value = contract;

            try
            {
                myCommand.Connection.Open();
                myCommand.ExecuteNonQuery();
           
            }
            catch (SqlException e)
            {
                if (e.Number == 2627)
                    throw new RecordExistException(“A record already exists with the same primary key”);
                else
                    throw new UnknownException();
            }
            finally
            {
                if (myCommand.Connection != null && myCommand.Connection.State == ConnectionState.Open)
                    myCommand.Connection.Close();
            }
           
        }
    }
}

 

  1. web.config:
    <configuration>
       <appSettings>
      <add key=”ConnectionString” value=”server=(local)\NetSDK;database=pubs;Trusted_Connection=yes”/>
      </appSettings>
    </configuration>

可以看出AuthorList.aspx.cs里纯粹是操作View里的对象以及Controller的编码,不再包含Model的编码。这些编码已经被移到另一个类,这个类完全可以属于一个新的类库项目。原先对SQL异常的处理,也改成了Model类抛出跟应用有关的异常。

当然,还有很多不满意之处,譬如AuthorList.aspx里的DataBinder.Eval里,还包含着数据库表的字段名(!),AuthorList.aspx.cs里对MyDataGrid里模板里的控件的处理也显得有些不干净。Author.cs类居然依赖System.Web (因为用了System.Web.HttpUtility类),SQL语句的处理也不满意,想象一下假如有很多这样的类的话,编码会有很多重复。依赖于web.config里的设置也不好,因为这样或多或少意味着这个类跟当前的aspx页的部署关系

【小题大做】 Antipattern: Magic Page

Bruce Tate 在他的书《Bitter Java》里谈到了Server-side Java 中的 antipatterns ,其中一个叫做“Magic Servlet” 。在这个Servlet 里,混杂了model,view和controller的编码,搞得责任不清,维护或扩展起来很麻烦。

其实在ASP.NET世界里也一样,如果你在论坛上混长了,类似下面的编码随处可见,我们不妨叫它为 “ Magic Page”, 。问题是,这些红字的语句是否应该出现在这里?

(:我知道这是个样品程序而已,求全责备恐怕是有点荒唐,但类似的编码在论坛上的帖子里经常出现,到底是什么原因呢?是程序员技术不精还是模仿造成的?)

<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SqlClient” %>

<html>

<head>

    SqlConnection myConnection;
    public Hashtable StateIndex;

    protected void Page_Load(Object Src, EventArgs E)
    {
        myConnection = new SqlConnection(“server=(local)\NetSDK;database=pubs;Trusted_Connection=yes”);

        if (!IsPostBack)
            BindGrid();

        StateIndex = new Hashtable();
        StateIndex[“CA”] = 0;
        StateIndex[“IN”] = 1;
        StateIndex[“KS”] = 2;
        StateIndex[“MD”] = 3;
        StateIndex[“MI”] = 4;
        StateIndex[“OR”] = 5;
        StateIndex[“TN”] = 6;
        StateIndex[“UT”] = 7;
    }

    public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
    {
        MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
        BindGrid();
    }

    public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
    {
        MyDataGrid.EditItemIndex = -1;
        BindGrid();
    }

    public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
    {
        if (Page.IsValid)
        {
            String updateCmd = “UPDATE Authors SET au_id = @Id, au_lname = @LName, au_fname = @FName, phone = @Phone, “
                + “address = @Address, city = @City, state = @State, zip = @Zip, contract = @Contract where au_id = @Id”;

            SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);

            myCommand.Parameters.Add(new SqlParameter(“@Id”, SqlDbType.NVarChar, 11));
            myCommand.Parameters.Add(new SqlParameter(“@LName”, SqlDbType.NVarChar, 40));
            myCommand.Parameters.Add(new SqlParameter(“@FName”, SqlDbType.NVarChar, 20));
            myCommand.Parameters.Add(new SqlParameter(“@Phone”, SqlDbType.NChar, 12));
            myCommand.Parameters.Add(new SqlParameter(“@Address”, SqlDbType.NVarChar, 40));
            myCommand.Parameters.Add(new SqlParameter(“@City”, SqlDbType.NVarChar, 20));
            myCommand.Parameters.Add(new SqlParameter(“@State”, SqlDbType.NChar, 2));
            myCommand.Parameters.Add(new SqlParameter(“@Zip”, SqlDbType.NChar, 5));
            myCommand.Parameters.Add(new SqlParameter(“@Contract”, SqlDbType.NVarChar,1));

            myCommand.Parameters[“@Id”].Value = MyDataGrid.DataKeys[(int)E.Item.ItemIndex];

            String[] cols = {“LName”,”FName”,”Phone”,”Address”,”City”,”Zip”};

            for (int i=0; i            {
                String colvalue = ((TextBox)E.Item.FindControl(“edit_” + cols[i])).Text;
                myCommand.Parameters[“@” + cols[i]].Value = Server.HtmlEncode(colvalue);
            }

            myCommand.Parameters[“@State”].Value = ((DropDownList)E.Item.FindControl(“edit_State”)).SelectedItem.ToString();

            if (((CheckBox)E.Item.FindControl(“edit_Contract”)).Checked = true)
                myCommand.Parameters[“@Contract”].Value = “1”;
            else
                myCommand.Parameters[“@Contract”].Value = “0”;

            myCommand.Connection.Open();

            try
            {
                myCommand.ExecuteNonQuery();
                Message.InnerHtml = “Record Updated
” + updateCmd;
                MyDataGrid.EditItemIndex = -1;
            }
            catch (SqlException e)
            {
                if (e.Number == 2627)
                    Message.InnerHtml = “ERROR: A record already exists with the same primary key”;
                else
                    Message.InnerHtml = “ERROR: Could not update record, please ensure the fields are correctly filled out”;
                Message.Style[“color”] = “red”;
            }

            myCommand.Connection.Close();

            BindGrid();
        }
        else
        {
            Message.InnerHtml = “ERROR: Please check each field for error conditions.”;
            Message.Style[“color”] = “red”;
        }
    }

    private void MyDataGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.EditItem)
        {
            for (int i = 0; i             {
                try
                {
                    if (e.Item.Controls[i].Controls[1].GetType().ToString() == “System.Web.UI.WebControls.TextBox”)
                    {
                        TextBox tb = (TextBox)e.Item.Controls[i].Controls[1];
                        tb.Text = Server.HtmlDecode(tb.Text);
                    }
                }
                catch
                {
                   
                }
            }
        }
    }

    public void BindGrid()
    {
        SqlDataAdapter myCommand = new SqlDataAdapter(“select * from Authors”, myConnection);

        DataSet ds = new DataSet();
        myCommand.Fill(ds, “Authors”);

        MyDataGrid.DataSource=ds.Tables[“Authors”].DefaultView;
        MyDataGrid.DataBind();
    }

</head>

<body style=”font: 10pt verdana”>

  <form runat=”server”>

    <h3><font face=”Verdana”>Updating a Row of Data w/ Validation</font></h3>

    <span id=”Message” EnableViewState=”false” style=”font: arial 11pt;” runat=”server”/><p>

    <ASP:DataGrid id=”MyDataGrid” runat=”server”
      Width=”800″
      BackColor=”#ccccff”
      BorderColor=”black”
      ShowFooter=”false”
      CellPadding=3
      CellSpacing=”0″
      Font-Name=”Verdana”
      Font-Size=”8pt”
      HeaderStyle-BackColor=”#aaaadd”
      OnEditCommand=”MyDataGrid_Edit”
      OnCancelCommand=”MyDataGrid_Cancel”
      OnUpdateCommand=”MyDataGrid_Update”
      DataKeyField=”au_id”
      AutoGenerateColumns=”false”
      OnItemDataBound=”MyDataGrid_ItemDataBound”
    >

      <Columns>
        <asp:EditCommandColumn EditText=”Edit” CancelText=”Cancel” UpdateText=”Update”  ItemStyle-Wrap=”false”/>
        <asp:BoundColumn HeaderText=”au_id” SortExpression=”au_id” ReadOnly=”True” DataField=”au_id” ItemStyle-Wrap=”false”/>
        <asp:TemplateColumn HeaderText=”au_lname” SortExpression=”au_lname”>
          <ItemTemplate>
            <asp:Label runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “au_lname”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <nobr>
            <asp:TextBox runat=”server” id=”edit_LName” Text='<%# DataBinder.Eval(Container.DataItem, “au_lname”) %>’/>
            <asp:RequiredFieldValidator id=”au_lnameReqVal”
                ControlToValidate=”edit_LName”
                Display=”Dynamic”
                Font-Name=”Verdana” Font-Size=”12″
                runat=server>
                    &nbsp;
            </asp:RequiredFieldValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”au_fname” SortExpression=”au_fname”>
          <ItemTemplate>
            <asp:Label runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “au_fname”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <nobr>
            <asp:TextBox runat=”server” id=”edit_FName” Text='<%# DataBinder.Eval(Container.DataItem, “au_fname”) %>’/>
            <asp:RequiredFieldValidator id=”au_fnameReqVal”
                ControlToValidate=”edit_FName”
                Display=”Dynamic”
                Font-Name=”Verdana” Font-Size=”12″
                runat=server>
                    &nbsp;

            </asp:RequiredFieldValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”phone” SortExpression=”phone”>
          <ItemTemplate>
            <asp:Label runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “phone”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <nobr>
            <asp:TextBox runat=”server” id=”edit_Phone” Text='<%# DataBinder.Eval(Container.DataItem, “phone”) %>’/>
            <asp:RequiredFieldValidator id=”phoneReqVal”
                ControlToValidate=”edit_Phone”
                Display=”Dynamic”
                Font-Name=”Verdana” Font-Size=”12″
                runat=server>
                    &nbsp;*
            </asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator id=”phoneRegexVal”
                ControlToValidate=”edit_Phone”
                ValidationExpression=”[0-9]{3} [0-9]{3}-[0-9]{4}”
                Display=”Dynamic”
                Font-Name=”Arial” Font-Size=”11″
                runat=server>
                    * Phone must be in form: XXX XXX-XXXX <br>
            </asp:RegularExpressionValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”address” SortExpression=”address”>
          <ItemTemplate>
            <asp:Label runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “address”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat=”server” id=”edit_Address” Text='<%# DataBinder.Eval(Container.DataItem, “address”) %>’/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”city” SortExpression=”city”>
          <ItemTemplate>
            <asp:Label runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “city”) %>’/>
   &n
bsp;      </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat=”server” id=”edit_City” Text='<%# DataBinder.Eval(Container.DataItem, “city”) %>’/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”state” SortExpression=”state”>
          <ItemTemplate>
            <asp:Label runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “state”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:DropDownList runat=”server” SelectedIndex=’<%# StateIndex[(String)((DataRowView)Container.DataItem)[“state”]] %>‘ id=”edit_State”>
                  <asp:ListItem>CA</asp:ListItem>
                  <asp:ListItem>IN</asp:ListItem>
                  <asp:ListItem>KS</asp:ListItem>
                  <asp:ListItem>MD</asp:ListItem>
                  <asp:ListItem>MI</asp:ListItem>
                  <asp:ListItem>OR</asp:ListItem>
                  <asp:ListItem>TN</asp:ListItem>
                  <asp:ListItem>UT</asp:ListItem>
            </asp:DropDownList>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”zip” SortExpression=”zip”>
          <ItemTemplate>
            <asp:Label runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “zip”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat=”server” id=”edit_Zip” Text='<%# DataBinder.Eval(Container.DataItem, “zip”) %>’/>
            <asp:RegularExpressionValidator id=”RegularExpressionValidator1″
                ASPClass=”RegularExpressionValidator” ControlToValidate=”edit_Zip”
                ValidationExpression=”[0-9]{5}”
                Display=”Dynamic”
                Font-Name=”Arial” Font-Size=”11″
                runat=server>
                    * Zip Code must be 5 numeric digits <br>
            </asp:RegularExpressionValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText=”contract” SortExpression=”contract”>
          <ItemTemplate>
            <asp:Label runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “contract”, “{0}”) %>’/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:CheckBox runat=”server” id=”edit_Contract” Checked='<%# DataBinder.Eval(Container.DataItem, “contract”) %>’/>
          </EditItemTemplate>
        </asp:TemplateColumn>
      </Columns>

    </ASP:DataGrid>

  </form>

</body>
</html>

跟本帖子的主题不相关,在上面的例程中,还有一个不懂的地方是,每次更新一条数据,为什么需要对整个DataGrid做DataBind()?为什么不能对当前这个DataGridItem做重新DataBind()?(DataGridItem是支持DataBind()的,但无法改变当前这个DataGridItem的ItemType)。。。。。。我的看法是,选择是否对整个DataGrid重新做DataBind()应该是高层次的policy,应该由应用的需求或程序员来决定,而不应该通过控件来强制执行