可编辑所有记录的 ASP.NET Gridview

标签 asp.net session gridview listview datatable

我以为这会很简单,但我确实在做这件事时遇到了很多麻烦:

这个问题的标题可能有点误导。我不必使用 gridview。事实上,我知道 GridView 可能不是解决这个问题的方法。我只是不知道如何命名它。但是,现在只需考虑:

我有一个非常简单的类,叫做 Student。它有4个属性: 整数编号 字符串 名字 字符串姓氏 字符串邮箱

我想在内存中保留这些的通用集合( session 状态): 列出学生;

好了,问题来了: 我希望用户根据需要创建尽可能多的 Student 对象。为了显示这些,我只想要一个简单的表格,每行有 3 个文本框。我希望每一行都有文本框而不是标签,以便可以随时编辑任何记录。

当用户完成创建他们的学生对象后,他们会继续做其他事情。但是,我只是找不到以这种方式显示记录的方法。我是否使用 ListView(3.5)、html 表格、gridview、转发器等?

你会怎么做?

最佳答案

为此,我个人倾向于使用 ListView,因为您可以用它插入行。您的 LayoutTemplate 将是一个包含 的表格。您的 ItemTemplate 将包含您的 TextBox(以及可选的每行保存按钮。然后,如果您还需要插入内容,您可以拥有一个 InsertItemTemplate。

您可以在页面的任何位置添加一个按钮来保存所有项目,方法是遍历 ListView.Item 集合并调用 ListView.Update(itemIndex, validate)。

<asp:ListView runat="server" ID="lv" InsertItemPosition="LastItem" DataKeyNames="id">
<LayoutTemplate>
    <asp:LinkButton runat="server" OnClick="SaveAll" Text="Save All" />
    <table>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
    </tr>
    <tr runat="server" id="itemPlaceHolder" />
    </table>
    <asp:LinkButton runat="server" OnClick="SaveAll" Text="Save All" />
</LayoutTemplate>
<ItemTemplate>
    <tr>
        <td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("firstName") %>' /></td>
        <td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("lastName") %>' /></td>
        <td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("email") %>' /></td>
        <td><asp:LinkButton runat="server" CommandName="update" Text="Save" /></td>
    </tr>
</ItemTemplate>
<InsertItemTemplate>
    <tr>
        <td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("firstName") %>' /></td>
        <td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("lastName") %>' /></td>
        <td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("email") %>' /></td>
        <td><asp:LinkButton runat="server" CommandName="insert" Text="Save" /></td>
    </tr>
</InsertItemTemplate>
</asp:ListView>

protected void SaveAll(object sender, EventArgs e)
{
    lv.Items.ToList().ForEach(li => lv.UpdateItem(li.DataItemIndex, true)_;
}

关于可编辑所有记录的 ASP.NET Gridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/583540/

相关文章:

c# - .Net session 范围变量?

java - Material 设计的 GridView 中未显示标高

html - Bootstrap grid .col 更高 - 相同的高度

c# - LocalTime 和 UniversalTime c# 之间的区别

asp.net - 自定义 asp.net 页面中的 Microsoft Communicator 存在指示器(状态指示器)

asp.net - 安装 ASP.NET 应用程序

node.js - Passport jwt 与 Passport 本地 session

python - Flask,在 View 之间传递用户输入的数据

C# : List image reset after close app

c# - cookie 第一次显示空值,再次访问该页面后,我可以看到 cookie 值。 ASP.NET C#