技术开发 频道

GridView中对鼠标单击某一独立单元格的编辑


    其它每一列的ItemTemplate中有一个可见的Label控件和一个不可见的TextBox或DropDownList控件。 为了方便,我们称Label为显示控件,TextBox或DropDownList为编辑控件。

<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>
    这里的办法就是用显示控件来显示数据,当单元格所包含的显示控件被单击的时候,则把显示控件的Visible属性设置为false并且把编辑控件的Visible属性设置为true。 这里不用使用EditItemTemplat。

    在RowDataBound事件内循环为每一数据行的每一单元格增加单击事件。 使用单元格在数据行中的索引作为事件参数,这样在单元格触发了单击事件后我们就可以知道到底是哪个单元格被单击了。

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;"; } } }
在RowCommand事件内读出命令参数和事件参数。 这会告诉我们被选中的行和列的索引。
int _rowIndex = int.Parse(e.CommandArgument.ToString()); int _columnIndex = int.Parse(Request.Form["__EVENTARGUMENT"]);
0
相关文章