65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET GridView - 添加新记录

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.39/5 (16投票s)

2005年12月19日

2分钟阅读

viewsIcon

465820

downloadIcon

1

ASP.NET GridView - 如何添加新记录。

引言

这段代码是为那些患有严重注意力缺陷多动障碍 (ADD) 的程序员准备的“快速抢夺”系列的一部分。我打赌还有很多其他程序员希望向他人提供代码,但只是不想花几个小时来创建一篇完整的“CodeProject”文章。这是尝试使一些有用的代码可供其他程序员使用,并在 10 分钟内完成。我鼓励其他人为“快速抢夺”做出贡献。

本系列的目的在于展示可用的预制类或技术,这些类或技术解决了实际问题,而无需过多地介绍其工作原理。我的意思是,谁真的关心 System.Collections.ArrayList 的工作原理,你只需要使用它。

请充分注释代码,以便真正关心(并且有时间)的人能够理解其底层算法。

使用代码

网络上有很多关于 ASP.NET 2.0 GridView 糟糕透顶的抱怨,因为它不支持插入操作,并且如果表源为空,网格甚至无法渲染。

这里有一个用不到 15 行代码的解决方案。

  • 像往常一样创建一个 GridView(我使用 NorthWind Categories 表作为示例)。
  • 创建数据源。
  • 更改
    SelectCommand="SELECT [CategoryID], [CategoryName]," + 
                " convert(nvarchar(1000),[Description]) FROM [Categories]";

    to

    SelectCommand="SELECT '' as [CategoryID], '' as [CategoryName]," + 
             " '' as [Description] UNION SELECT [CategoryID]," + 
             " [CategoryName], convert(nvarchar(1000),[Description])" + 
             " FROM [Categories]";

    这会将一个空行作为网格的第一行插入。

    这是你将要编辑以添加新记录的行。

  • Add
    OnRowUpdating="GridView1_RowAdding";

    作为网格的事件(你可以通过 GUI 完成)。

  • 添加高亮的 JavaScript 代码。

    它找到第一个“编辑 删除”文本并将其更改为“添加”。

  • 添加“GridView1_RowAdding”方法。

OnRowUpdatingGridView 在更新行之前调用。GridView 认为它正在更新 CategoryID=0(这将无声地失败)。与此同时,你正在获取数据并进行秘密插入。

<%@ Page Language="C#" AutoEventWireup="true" 
             CodeFile="AddUpdate.aspx.cs" Inherits="AddUpdate" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script>
    function FixGrid(idGrid)
    {
      // content looks like:
      //"<A href=\"javascript:__doPostBack('GridView1',
      //    'Edit$0')\">Edit</A> 
      // <A href=\"javascript:__doPostBack('GridView1',
      //    'Delete$0')\">Delete</A>"
      // replace Edit with Add, remove Delete
      var Parts = 
       idGrid.firstChild.childNodes[1].childNodes[0].innerHTML.split(">Edit<");
      var tmp = Parts.join(">Add<"); 
      Parts = tmp.split(">Delete<");
      idGrid.firstChild.childNodes[1].childNodes[0].innerHTML = 
                                        Parts.join("><");
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" 
                 AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" 
                    OnRowUpdating="GridView1_RowAdding">
            <Columns>
                <asp:CommandField ShowDeleteButton="True" 
                    ShowEditButton="True" />
                <asp:BoundField DataField="CategoryID" 
                    HeaderText="CategoryID" InsertVisible="False"
                    ReadOnly="True" SortExpression="CategoryID" />
                <asp:BoundField DataField="CategoryName" 
                       HeaderText="CategoryName" 
                       SortExpression="CategoryName" />
                <asp:BoundField DataField="Description" 
                       HeaderText="Description" 
                       SortExpression="Description" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
              ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            DeleteCommand="DELETE FROM [Categories] 
                           WHERE [CategoryID] = @CategoryID"
            InsertCommand="INSERT INTO [Categories] 
                           ([CategoryName], [Description]) 
                           VALUES (@CategoryName, @Description)"
            SelectCommand="SELECT '' as [CategoryID], 
                '' as [CategoryName], '' as [Description]
                UNION SELECT [CategoryID], [CategoryName], 
                convert(nvarchar(1000),[Description])
                FROM [Categories]" 
            UpdateCommand="UPDATE [Categories] SET 
                           [CategoryName] = @CategoryName, 
                           [Description] = @Description 
                           WHERE [CategoryID] = @CategoryID">
            <DeleteParameters>
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
    
    </div>
    </form>
        <script>
            FixGrid(document.all.GridView1);
        </script>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AddUpdate : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void GridView1_RowAdding(object sender, 
                        GridViewUpdateEventArgs e)
    {
        if (e.RowIndex > 0)
            return; // RowIndex=0 is the row we want to insert
        System.Collections.Hashtable h = 
                    new System.Collections.Hashtable();

        foreach (System.Collections.DictionaryEntry x in e.NewValues)
        {
            h[x.Key] = x.Value;
        }
        // you now have the data to insert in a hashtable
        // get it into the database using your
        // usual Data Access Layer methods

    }
}
© . All rights reserved.