ASP.NET GridView - Add a new record
来源:互联网 发布:晨风颜涛授权空间源码 编辑:程序博客网 时间:2024/05/20 08:01
Introduction
This code drop is part of a Smash and Grab series for the seriously ADD (Attention Deficit Disorder) programmer. I'll bet there are a lot of other programmers out there who would like to make code available to others, but just don't want to spend the hours required to create a full-blown "CodeProject" article. This is an attempt to see if I can make some useful code available to other programmers, and do it in 10 minutes. I encourage others to contribute to "Smash and Grab".
The point of this series is to present usable pre-canned classes or techniques which solve a real world problem without going into too much detail about how it works. I mean, who really cares about how System.Collections.ArrayList
works, you just use it.
Please fully comment the code so that the person who really cares (and has the time) will be able to understand the underlying algorithm.
Using the code
There has been a lot of whining on the net about what a train-wreck the ASP.NET 2.0 GridView
is because it won't do inserts and if the table source is empty, the grid does not even render.
Here is a solution in less than 15 lines of code.
- Create a
GridView
as usual (I am using the NorthWind Categories table as an example). - Create the data source.
- Change:
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]";
This inserts a blank row as the first line of the grid.
This is the line that you will be editing to add the new record.
- Add:
OnRowUpdating="GridView1_RowAdding";
as an event to the grid (you can do it through the GUI).
- Add the highlighted JavaScript code.
It finds the first "Edit Delete" text and changes it to "Add".
- Add the "
GridView1_RowAdding
" method.
OnRowUpdating
is called by the GridView
before it updates a row. The GridView
thinks it is doing an update to CategoryID
=0 (which will silently fail). Meanwhile, you are scooping the data and doing a secret insert.
<%@ 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 }}
- ASP.NET GridView - Add a new record
- How to add a new record to an IQueryable variable?
- Use the GridView to insert a new record
- add a new one
- Add a New Module
- extend crash command "net" and add a new command "flow"
- Developing a Multi-Select ASP.NET GridView using JQuery
- How to Create a Second Level GridView in ASP.NET
- asp.net 获取GridView中a标签并进行操作
- creates a new user for an ASP.NET application
- “Razor” – a new view engine for ASP.NET
- Introducing “Razor” – a new view engine for ASP.NET
- ASP.NET GridView 有多強?
- gridview分页(asp.net)
- asp.net gridview控件
- asp.net 绑定GridView
- asp.net GridView 应用
- ASP.net Gridview 使用指南
- .NET三层经典架构PetShop3.0分析之表现层
- petshop3.0--多层应用架构
- int与string
- Microsoft 数据仓库架构
- 关于溢出漏洞的真实例子(原创)
- ASP.NET GridView - Add a new record
- String 或 StringBuilder
- 学习反射机制 c#
- CToolTipCtrl的用法(静态地显示工具提示)
- Subversion安装手记
- 学习Ajax做的一个异步调用例子
- 如何解决页面之间传输中文乱码的问题
- 使用Webwork 2.2.4实现文件上传
- 慎用Webwork的getText,使用不当效率可能会很低