更新数据库在 Web 应用程序中可能经常很棘手。针对这种情况,DataGrid 控件提供了一些使更新更容易的内置支持。为了允许对行进行编辑,DataGrid 支持整型 EditItemIndex 属性,该属性指示网格的哪一行应该是可编辑的。设置了该属性后,DataGrid 按该索引将行呈现为文本输入框,而不是简单的标签。值 -1(默认值)指示没有行是可编辑的。页可以在服务器端窗体中包含 DataGrid,并通过 DataGrid 的对象模型获取对编辑数据的访问。
为了确定哪一行应该是可编辑的,需要一种方法接受用户关于他们希望编辑哪一行的输入。DataGrid 可以包含一个 EditCommandColumn 来呈现激发三个特殊事件的链接:EditCommand、UpdateCommand 和 CancelCommand。EditCommandColumn 以声明方式添加到 DataGrid 的 Columns 集合,如下面的示例所示。
<ASP:DataGrid id="MyDataGrid" runat="server"
...
OnEditCommand="MyDataGrid_Edit"
OnCancelCommand="MyDataGrid_Cancel"
OnUpdateCommand="MyDataGrid_Update"
DataKeyField="au_id"
>
<Columns>
<asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" />
</Columns>
</ASP:DataGrid>
在 DataGrid 标记本身上,将事件处理程序连到从 EditCommandColumn 激发的每个命令。这些处理程序的 DataGridCommandEventArgs 参数使您得以直接访问由用来设置 DataGrid 的 EditItemIndex 的客户端选择的索引。注意,需要重新绑定 DataGrid 以使更改生效,如下面的示例所示。
public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E) {
MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
BindGrid();
}
Public Sub MyDataGrid_Edit(sender As Object, E As DataGridCommandEventArgs)
MyDataGrid.EditItemIndex = E.Item.ItemIndex
BindGrid()
End Sub
public function MyDataGrid_Edit(sender:Object, E:DataGridCommandEventArgs) : void {
MyDataGrid.EditItemIndex = int(E.Item.ItemIndex);
BindGrid();
}
当编辑某行 DataGrid 时,EditCommandColumn 呈现 Update 和 Cancel 链接。如果客户端选择 Cancel,只需将 EditItemIndex 设置回 -1。但如果客户端选择 Update,则需要对数据库执行更新命令。执行更新查询要求知道希望更新的行的数据库中的主键。为支持此要求,DataGrid 公开一个可以设置为主键字段名的 DataKeyField 属性。在连到 UpdateCommand 的事件处理程序中,可以从 DataGrid 的 DataKeys 集合检索键名。使用事件的 ItemIndex 在此集合中索引,如下面的示例所示。
myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
myCommand.Parameters("@Id").Value = MyDataGrid.DataKeys(CType(E.Item.ItemIndex, Integer))
myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[int(E.Item.ItemIndex)];
在 Update 事件处理程序的最后,将 EditItemIndex 设置回 -1。下面的示例说明此代码的运行。
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
SqlConnection myConnection;
protected void Page_Load(Object Src, EventArgs E)
{
myConnection=new SqlConnection("server=jeff;uid=sa;password=;database=pubs");
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)
{
String updateCmd = "UPDATE Authors SET 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 = {"@Id","@LName","@FName","@Phone","@Address","@City","@State","@Zip","@Contract"};
int numCols = e.Item.Cells.Count;
for (int i=2; i<numCols-1; i++) //跳过第一、第二和最后一列
{
String colvalue =((TextBox)e.Item.Cells[i].Controls[0]).Text;
// 检查在所需字段中是否有空值
if (i<6 && colvalue == "")
{
Message.InnerHtml = "错误:“作者 ID”、“姓名”或“电话”不允许使用空值";
Message.Style["color"] = "red";
return;
}
myCommand.Parameters[cols[i-1]].Value = colvalue;
}
//追加最后一行,将 true/false 值转换为 0/1
if (String.Compare(((TextBox)e.Item.Cells[numCols-1].Controls[0]).Text, "True", true)==0)
myCommand.Parameters["@Contract"].Value ="1";
else
myCommand.Parameters["@Contract"].Value ="0";
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
Message.InnerHtml = "<b>已更新记录</b><br>" + updateCmd;
MyDataGrid.EditItemIndex = -1;
}
catch (SqlException exc)
{
if (exc.Number == 2627)
Message.InnerHtml = "错误:已存在具有相同主键的记录";
else
Message.InnerHtml = "错误:未能更新记录,请确保正确填写了字段";
Message.Style["color"] = "red";
}
myCommand.Connection.Close();
BindGrid();
}
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();
}
</script>
<body style="font: 10.5pt 宋体">
<form runat="server" ID="Form1">
<h3><font face="宋体">更新数据行</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">
<Columns>
<asp:EditCommandColumn EditText="编辑" CancelText="取消" UpdateText="更新" ItemStyle-Wrap="false" />
</Columns>
</ASP:DataGrid>
</form>
</body>
</html>
前一示例的一个问题是,当行可编辑时,主键字段 (au_id) 也呈现为文本输入框。您不希望客户端更改该值,因为需要它来确定更新数据库中的哪一行。幸运的是,可以通过精确指定每一列相对于可编辑行的外观,禁用将此列呈现为文本框。为此需在 DataGrid 的 Columns 集合中定义每一行,使用 BoundColumn 控件分配每一列的数据字段。使用此方法,您可以完全控制列的顺序,以及它们的 ReadOnly 属性。对于 au_id 列,将 ReadOnly 属性设置为 true。当行处于编辑模式时,此列将继续呈现为标签。下面的示例说明此方法。
aspx文件里面加入DataGrid控件半设置属性,代码如下:
<body MS_POSITIONING="GridLayout">
<form id="form7" method="post" runat="server">
<asp:Literal id="Message" runat="server"></asp:Literal>
<ASP:DataGrid id="DataGrid1" 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">
<Columns>
<asp:EditCommandColumn EditText="编辑" CancelText="取消" UpdateText="更新" ItemStyle-Wrap="false" />
<asp:BoundColumn HeaderText="au_id" SortExpression="au_id" ReadOnly="True" DataField="au_id" ItemStyle-Wrap="false" />
<asp:BoundColumn HeaderText="au_lname" SortExpression="au_lname" DataField="au_lname" />
<asp:BoundColumn HeaderText="au_fname" SortExpression="au_fname" DataField="au_fname" />
<asp:BoundColumn HeaderText="phone" SortExpression="phone" DataField="phone" />
<asp:BoundColumn HeaderText="address" SortExpression="address" DataField="address" />
<asp:BoundColumn HeaderText="city" SortExpression="city" DataField="city" />
<asp:BoundColumn HeaderText="state" SortExpression="state" DataField="state" />
<asp:BoundColumn HeaderText="zip" SortExpression="zip" DataField="zip" />
<asp:BoundColumn HeaderText="contract" SortExpression="contract" DataField="contract" />
</Columns>
</ASP:DataGrid>
</form>
</body>
aspx.cs文件中加入下面代码:
导入using System.Data.SqlClient;
定义SqlConnection myConnection;
private void Page_Load(object sender, System.EventArgs e)
{
myConnection = new SqlConnection("user id=sa;password=;initial catalog=pubs;data source=jeff");
if (!IsPostBack)
BindGrid();
}
public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
{
DataGrid1.EditItemIndex = (int)E.Item.ItemIndex;
BindGrid();
}
public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
{
DataGrid1.EditItemIndex = -1;
BindGrid();
}
public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
{
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 = DataGrid1.DataKeys[(int)E.Item.ItemIndex];
String[] cols = {"@Id","@LName","@FName","@Phone","@Address","@City","@State","@Zip","@Contract"};
int numCols = E.Item.Cells.Count;
for (int i=2; i<numCols-1; i++) //跳过第一、第二和最后一列
{
String colvalue =((TextBox)E.Item.Cells[i].Controls[0]).Text;
// 检查在所需字段中是否有空值
if (i<6 && colvalue == "")
{
Message.Text = "错误:“作者 ID”、“姓名”或“电话”不允许使用空值";
return;
}
myCommand.Parameters[cols[i-1]].Value = colvalue;
}
//追加最后一行,将 true/false 值转换为 0/1
if (String.Compare(((TextBox)E.Item.Cells[numCols-1].Controls[0]).Text, "True", true)==0)
myCommand.Parameters["@Contract"].Value ="1";
else
myCommand.Parameters["@Contract"].Value ="0";
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
Message.Text = "<b>已更新记录</b><br>" + updateCmd;
DataGrid1.EditItemIndex = -1;
}
catch (SqlException e)
{
if (e.Number == 2627)
Message.Text = "错误:已存在具有相同主键的记录";
else
Message.Text = "错误:未能更新记录,请确保正确填写了字段";
}
myCommand.Connection.Close();
BindGrid();
}
public void BindGrid()
{
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");
DataGrid1.DataSource=ds.Tables["Authors"].DefaultView;
DataGrid1.DataBind();
}
一例中BoundColumn 控件不是唯一可以在 DataGrid 的 Columns 集合中设置的控件。还可以指定 TemplateColumn,它使您可以完全控制列的内容。模板的内容可以是任意的;在 DataGrid 的列中可以呈现任何内容,包括服务器控件。下面的示例说明如何使用 TemplateColumn 控件将“State”列呈现为下拉列表并将“Contract”列呈现为复选框 HtmlControl。ASP.NET 数据绑定语法用于输出模板中的数据字段值。注意,有一些棘手的逻辑使下拉列表和复选框反射行中的数据状态。
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
SqlConnection myConnection;
public Hashtable StateIndex;
protected void Page_Load(Object Src, EventArgs E)
{
myConnection = new SqlConnection("user id=sa;password=;initial catalog=pubs;data source=jeff");
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 int GetStateIndex(String stateName)
{
if (StateIndex[stateName] != null)
return (int)StateIndex[stateName];
else
return 0;
}
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)
{
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<6; i++)
{
String colvalue = ((TextBox)E.Item.FindControl("edit_" + cols[i])).Text;
// 检查在所需字段中是否有空值
if (i<3 && colvalue == "")
{
Message.InnerHtml = "错误:“姓名”或“电话”不允许使用空值";
Message.Style["color"] = "red";
return;
}
myCommand.Parameters["@" + cols[i]].Value = 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 = "<b>已更新记录</b><br>" + updateCmd;
MyDataGrid.EditItemIndex = -1;
}
catch (SqlException e)
{
if (e.Number == 2627)
Message.InnerHtml = "错误:已存在具有相同主键的记录";
else
Message.InnerHtml = "错误:未能更新记录,请确保正确填写了字段";
Message.Style["color"] = "red";
}
myCommand.Connection.Close();
BindGrid();
}
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();
}
</script>
<body style="font: 10.5pt 宋体">
<form runat="server">
<h3><font face="宋体">更新具有模板列的数据行</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"
>
<Columns>
<asp:EditCommandColumn EditText="编辑" CancelText="取消" UpdateText="更新"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>
<asp:TextBox runat="server" id="edit_LName" Text="<%# DataBinder.Eval(Container.DataItem, "au_lname") %>"/>
</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>
<asp:TextBox runat="server" id="edit_FName" Text="<%# DataBinder.Eval(Container.DataItem, "au_fname") %>"/>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="phone" SortExpression="phone">
<ItemTemplate>
<asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "phone") %>"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" id="edit_Phone" Text="<%# DataBinder.Eval(Container.DataItem, "phone") %>"/>
</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") %>"/>
</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="<%# GetStateIndex(DataBinder.Eval(Container.DataItem, "state").ToString()) %>" 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") %>"/>
</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 可以包含一个 EditCommandColumn 来呈现激发三个特殊事件的链接:EditCommand、UpdateCommand 和 CancelCommand。EditCommandColumn 以声明方式添加到 DataGrid 的 Columns 集合,如下面的示例所示。
<ASP:DataGrid id="MyDataGrid" runat="server"
...
OnEditCommand="MyDataGrid_Edit"
OnCancelCommand="MyDataGrid_Cancel"
OnUpdateCommand="MyDataGrid_Update"
DataKeyField="au_id"
>
<Columns>
<asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" />
</Columns>
</ASP:DataGrid>
在 DataGrid 标记本身上,将事件处理程序连到从 EditCommandColumn 激发的每个命令。这些处理程序的 DataGridCommandEventArgs 参数使您得以直接访问由用来设置 DataGrid 的 EditItemIndex 的客户端选择的索引。注意,需要重新绑定 DataGrid 以使更改生效,如下面的示例所示。
public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E) {
MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
BindGrid();
}
Public Sub MyDataGrid_Edit(sender As Object, E As DataGridCommandEventArgs)
MyDataGrid.EditItemIndex = E.Item.ItemIndex
BindGrid()
End Sub
public function MyDataGrid_Edit(sender:Object, E:DataGridCommandEventArgs) : void {
MyDataGrid.EditItemIndex = int(E.Item.ItemIndex);
BindGrid();
}
当编辑某行 DataGrid 时,EditCommandColumn 呈现 Update 和 Cancel 链接。如果客户端选择 Cancel,只需将 EditItemIndex 设置回 -1。但如果客户端选择 Update,则需要对数据库执行更新命令。执行更新查询要求知道希望更新的行的数据库中的主键。为支持此要求,DataGrid 公开一个可以设置为主键字段名的 DataKeyField 属性。在连到 UpdateCommand 的事件处理程序中,可以从 DataGrid 的 DataKeys 集合检索键名。使用事件的 ItemIndex 在此集合中索引,如下面的示例所示。
myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
myCommand.Parameters("@Id").Value = MyDataGrid.DataKeys(CType(E.Item.ItemIndex, Integer))
myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[int(E.Item.ItemIndex)];
在 Update 事件处理程序的最后,将 EditItemIndex 设置回 -1。下面的示例说明此代码的运行。
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
SqlConnection myConnection;
protected void Page_Load(Object Src, EventArgs E)
{
myConnection=new SqlConnection("server=jeff;uid=sa;password=;database=pubs");
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)
{
String updateCmd = "UPDATE Authors SET 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 = {"@Id","@LName","@FName","@Phone","@Address","@City","@State","@Zip","@Contract"};
int numCols = e.Item.Cells.Count;
for (int i=2; i<numCols-1; i++) //跳过第一、第二和最后一列
{
String colvalue =((TextBox)e.Item.Cells[i].Controls[0]).Text;
// 检查在所需字段中是否有空值
if (i<6 && colvalue == "")
{
Message.InnerHtml = "错误:“作者 ID”、“姓名”或“电话”不允许使用空值";
Message.Style["color"] = "red";
return;
}
myCommand.Parameters[cols[i-1]].Value = colvalue;
}
//追加最后一行,将 true/false 值转换为 0/1
if (String.Compare(((TextBox)e.Item.Cells[numCols-1].Controls[0]).Text, "True", true)==0)
myCommand.Parameters["@Contract"].Value ="1";
else
myCommand.Parameters["@Contract"].Value ="0";
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
Message.InnerHtml = "<b>已更新记录</b><br>" + updateCmd;
MyDataGrid.EditItemIndex = -1;
}
catch (SqlException exc)
{
if (exc.Number == 2627)
Message.InnerHtml = "错误:已存在具有相同主键的记录";
else
Message.InnerHtml = "错误:未能更新记录,请确保正确填写了字段";
Message.Style["color"] = "red";
}
myCommand.Connection.Close();
BindGrid();
}
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();
}
</script>
<body style="font: 10.5pt 宋体">
<form runat="server" ID="Form1">
<h3><font face="宋体">更新数据行</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">
<Columns>
<asp:EditCommandColumn EditText="编辑" CancelText="取消" UpdateText="更新" ItemStyle-Wrap="false" />
</Columns>
</ASP:DataGrid>
</form>
</body>
</html>
前一示例的一个问题是,当行可编辑时,主键字段 (au_id) 也呈现为文本输入框。您不希望客户端更改该值,因为需要它来确定更新数据库中的哪一行。幸运的是,可以通过精确指定每一列相对于可编辑行的外观,禁用将此列呈现为文本框。为此需在 DataGrid 的 Columns 集合中定义每一行,使用 BoundColumn 控件分配每一列的数据字段。使用此方法,您可以完全控制列的顺序,以及它们的 ReadOnly 属性。对于 au_id 列,将 ReadOnly 属性设置为 true。当行处于编辑模式时,此列将继续呈现为标签。下面的示例说明此方法。
aspx文件里面加入DataGrid控件半设置属性,代码如下:
<body MS_POSITIONING="GridLayout">
<form id="form7" method="post" runat="server">
<asp:Literal id="Message" runat="server"></asp:Literal>
<ASP:DataGrid id="DataGrid1" 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">
<Columns>
<asp:EditCommandColumn EditText="编辑" CancelText="取消" UpdateText="更新" ItemStyle-Wrap="false" />
<asp:BoundColumn HeaderText="au_id" SortExpression="au_id" ReadOnly="True" DataField="au_id" ItemStyle-Wrap="false" />
<asp:BoundColumn HeaderText="au_lname" SortExpression="au_lname" DataField="au_lname" />
<asp:BoundColumn HeaderText="au_fname" SortExpression="au_fname" DataField="au_fname" />
<asp:BoundColumn HeaderText="phone" SortExpression="phone" DataField="phone" />
<asp:BoundColumn HeaderText="address" SortExpression="address" DataField="address" />
<asp:BoundColumn HeaderText="city" SortExpression="city" DataField="city" />
<asp:BoundColumn HeaderText="state" SortExpression="state" DataField="state" />
<asp:BoundColumn HeaderText="zip" SortExpression="zip" DataField="zip" />
<asp:BoundColumn HeaderText="contract" SortExpression="contract" DataField="contract" />
</Columns>
</ASP:DataGrid>
</form>
</body>
aspx.cs文件中加入下面代码:
导入using System.Data.SqlClient;
定义SqlConnection myConnection;
private void Page_Load(object sender, System.EventArgs e)
{
myConnection = new SqlConnection("user id=sa;password=;initial catalog=pubs;data source=jeff");
if (!IsPostBack)
BindGrid();
}
public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
{
DataGrid1.EditItemIndex = (int)E.Item.ItemIndex;
BindGrid();
}
public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
{
DataGrid1.EditItemIndex = -1;
BindGrid();
}
public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
{
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 = DataGrid1.DataKeys[(int)E.Item.ItemIndex];
String[] cols = {"@Id","@LName","@FName","@Phone","@Address","@City","@State","@Zip","@Contract"};
int numCols = E.Item.Cells.Count;
for (int i=2; i<numCols-1; i++) //跳过第一、第二和最后一列
{
String colvalue =((TextBox)E.Item.Cells[i].Controls[0]).Text;
// 检查在所需字段中是否有空值
if (i<6 && colvalue == "")
{
Message.Text = "错误:“作者 ID”、“姓名”或“电话”不允许使用空值";
return;
}
myCommand.Parameters[cols[i-1]].Value = colvalue;
}
//追加最后一行,将 true/false 值转换为 0/1
if (String.Compare(((TextBox)E.Item.Cells[numCols-1].Controls[0]).Text, "True", true)==0)
myCommand.Parameters["@Contract"].Value ="1";
else
myCommand.Parameters["@Contract"].Value ="0";
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
Message.Text = "<b>已更新记录</b><br>" + updateCmd;
DataGrid1.EditItemIndex = -1;
}
catch (SqlException e)
{
if (e.Number == 2627)
Message.Text = "错误:已存在具有相同主键的记录";
else
Message.Text = "错误:未能更新记录,请确保正确填写了字段";
}
myCommand.Connection.Close();
BindGrid();
}
public void BindGrid()
{
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");
DataGrid1.DataSource=ds.Tables["Authors"].DefaultView;
DataGrid1.DataBind();
}
一例中BoundColumn 控件不是唯一可以在 DataGrid 的 Columns 集合中设置的控件。还可以指定 TemplateColumn,它使您可以完全控制列的内容。模板的内容可以是任意的;在 DataGrid 的列中可以呈现任何内容,包括服务器控件。下面的示例说明如何使用 TemplateColumn 控件将“State”列呈现为下拉列表并将“Contract”列呈现为复选框 HtmlControl。ASP.NET 数据绑定语法用于输出模板中的数据字段值。注意,有一些棘手的逻辑使下拉列表和复选框反射行中的数据状态。
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
SqlConnection myConnection;
public Hashtable StateIndex;
protected void Page_Load(Object Src, EventArgs E)
{
myConnection = new SqlConnection("user id=sa;password=;initial catalog=pubs;data source=jeff");
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 int GetStateIndex(String stateName)
{
if (StateIndex[stateName] != null)
return (int)StateIndex[stateName];
else
return 0;
}
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)
{
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<6; i++)
{
String colvalue = ((TextBox)E.Item.FindControl("edit_" + cols[i])).Text;
// 检查在所需字段中是否有空值
if (i<3 && colvalue == "")
{
Message.InnerHtml = "错误:“姓名”或“电话”不允许使用空值";
Message.Style["color"] = "red";
return;
}
myCommand.Parameters["@" + cols[i]].Value = 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 = "<b>已更新记录</b><br>" + updateCmd;
MyDataGrid.EditItemIndex = -1;
}
catch (SqlException e)
{
if (e.Number == 2627)
Message.InnerHtml = "错误:已存在具有相同主键的记录";
else
Message.InnerHtml = "错误:未能更新记录,请确保正确填写了字段";
Message.Style["color"] = "red";
}
myCommand.Connection.Close();
BindGrid();
}
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();
}
</script>
<body style="font: 10.5pt 宋体">
<form runat="server">
<h3><font face="宋体">更新具有模板列的数据行</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"
>
<Columns>
<asp:EditCommandColumn EditText="编辑" CancelText="取消" UpdateText="更新"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>
<asp:TextBox runat="server" id="edit_LName" Text="<%# DataBinder.Eval(Container.DataItem, "au_lname") %>"/>
</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>
<asp:TextBox runat="server" id="edit_FName" Text="<%# DataBinder.Eval(Container.DataItem, "au_fname") %>"/>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="phone" SortExpression="phone">
<ItemTemplate>
<asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "phone") %>"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" id="edit_Phone" Text="<%# DataBinder.Eval(Container.DataItem, "phone") %>"/>
</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") %>"/>
</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="<%# GetStateIndex(DataBinder.Eval(Container.DataItem, "state").ToString()) %>" 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") %>"/>
</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>