作者:Declan Bright
翻译:webabcd
【IT168 技术文档】
介绍
ASP.NET的GridView控件允许你通过设置它的EditIndex属性来编辑数据行,此时整个数据行都处于编辑模式。 如果你在EditItemTemplate的一些列中使用了DropDownList控件,那么你也许不希望整个数据行都处于编辑模式。 因为,如果每一个DropDownList控件都有很多选项的话,那么一次加载所有DropDownList控件的所有选项就会导致页面执行缓慢。
另外,如果你的数据行的编辑模式需要占用更多的空间的话,那么针对每一个独立的单元格进行编辑要优于针对整个数据行进行编辑。 这里,我将示范如何实现这样的功能,又如何去处理事件验证(event validation)。
背景
本文基于我之前写的一篇文章:GridView和DataList响应单击数据行和双击数据行事件。如果你不知道如何让GridView响应单击数据行事件,那么你可以在阅读本文之前先看看这篇文章。
编辑某一个独立的GridView单元格。
我所演示的这个GridView有一个不可见的asp:ButtonField控件,它处于GridView的第一列,名为“SingleClick”。 它用于给GridView的数据行增加单击事件。
<Columns>
<asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False" />
</Columns>
<asp:TemplateField HeaderText="Task">
<ItemTemplate>
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
<asp:TextBox ID="Description" runat="server" Text='<%# Eval("Description") %>' Width="175px" visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// 从第一个单元格内获得LinkButton控件
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
// 返回一个字符串,表示对包含目标控件的 ID 和事件参数的回发函数的 JavaScript 调用
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
// 给每一个可编辑的单元格增加事件
for (int columnIndex = _firstEditCellIndex; columnIndex < e.Row.Cells.Count; columnIndex++)
{
// 增加列索引作为事件参数
string js = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString());
// 给单元格增加onclick事件
e.Row.Cells[columnIndex].Attributes["onclick"] = js;
// 给单元格增加鼠标经过时指针样式
e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";
}
}
}
int _rowIndex = int.Parse(e.CommandArgument.ToString());
int _columnIndex = int.Parse(Request.Form["__EVENTARGUMENT"]);