asp.net 自定义 Gridview,仅对单击的单元格切换到编辑模式

asp.net custom Gridview which switch to edit mode only for clicked cell

我正在尝试创建自定义 GridView 服务器控件,因为我只想进入选定的编辑模式 cell.this 是我的代码,但它不起作用

  protected override void Render(HtmlTextWriter writer)
    {
        foreach (GridViewRow r in this.Rows)
        {
            if (r.RowType == DataControlRowType.DataRow)
           {
                for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++)
                {
        r.Cells[columnIndex].Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(this, "Edit$" + r.Cells[columnIndex], true);

                }
           }
        }
        base.Render(writer);  

    }

有人能帮忙吗

默认情况下,Gridview 一次只允许您编辑一行。这对每一行都是一个全有或全无的交易,当然假设你的 none 列被标记为 ReadOnly.

其次,编辑事件本身是基于行而不是基于单元格的,因此要获得您想要的功能,您必须创建自己的更新例程,遍历每行的每个单元格并相应地更新您的数据存储

I want to say that just because you can do something doesn't necessarily mean you should. This is a complete abomination of a very widely used control. So, that said, the fact that we can do this is, IMO, a testament to the control designers.

在 Gridview 的设计器中,将所有可编辑字段转换为模板字段并且不要添加任何 Selection/Edit/Update/Delete/Insert 命令控件。这些是基于行的操作,您希望避免这种情况,尤其是编辑。您将不得不编写自己的例程 - 见上文

然后切换到“源代码”视图(从此处执行下一部分更容易)

  1. 删除<ItemTemplate>
  2. 的内容
  3. <EditItemTemplate> 的内容移动到 <ItemTemplate>
  4. 删除所有 <EditItemTemplate> - 此时不需要它们
  5. 使每个可编辑控件只读,即:<asp:TextBox ID="tbxWhatever" runat="server" Text='Bind("some_field_name")' ReadOnly="True"

现在您在上面所做的是将编辑模式控件移动到通常是 GridView 的只读部分。随意更改或使用适合您目的的任何控件。

要获得您想要的功能,您需要添加启用该控件的 js 事件处理程序。我建议通过 RowCreated 事件向每个可编辑控件添加一个 onclick 处理程序,例如

<asp:TextBox ID="tbxWhatever" runat="server" Text='Bind("some_field_name")' 
        Enabled="False" 
        onclick="EnableMe(this)"

代码隐藏(VB):

Private Sub Gridview1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles Gridview1.RowCreated
    dim gv as GridView = sender
    dim tbx as TextBox = gv.FindControl("tbxWhatever")
    tbx.Attributes.Add("onclick", "EnableMe(this);")
End Sub

在某些 <script> 标签或关联的 .js 代码文件中存在这个:

function EnableMe( elem ) {
  elem.readOnly= (! elem.readOnly);
}

最后,您需要在页面的某个位置放置一个保存按钮。如果你使用标准的 Button 或 ImageButton 你应该没问题。将 CommandName 参数设置为合适的值并在后面的代码中处理按钮的 Command 事件。这是您执行自定义保存例程的地方。

祝你好运。

PS:关于您希望创建在单元格级别运行的 GridView 的某些派生版本,您想要的更像是电子表格或 DataGrid 而不是 asp:Gridview.您可能想找到一个更好的起点。