在DataGrid快速添加新行

类别:.NET开发 点击:0 评论:0 推荐:
在DataGrid快速添加新行
作者:孟宪会 出自:【孟宪会之精彩世界】 发布日期:2003年5月13日 1点26分31秒

ASP.NET DataGrid为我们提供的内建的记录行编辑功能,但是没有提供内建的添加新行的功能。一个办法就是:在DataTable中添加新行,然后再重新绑定到DataGrid,这个办法可行,但在更新前需要进行确认,可能会产生空行。另外一个解决办法就是:利用DataGrid footer template来提供一个空的行,这样既可以提高速度,也可以避免其它方法带来的不足。

为了为浏览者提供一个空行,我们使用DataGrid的Footer Template,我们直接在Footer Template里添加文本框,这样可以避免不必要的操作:比如点击“编辑”按钮等。这样也可以减少往复数据提交的次数。我们这里仍然LinkButton(插入),并设置CommandName属性为“Insert”,这个CommandName在DataGrid的ItemCommand事件中,确保只有用户点击了“Insert”LinkButton才添加记录。添加到数据库的方法是很简单的。

下面的这个例子提供了DataGrid快速添加新行的功能。aspx代码和Cohe Behind代码分别如下,注意更改数据录连接字符串:

查看例子

InsertableDataGrid.aspx

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="InsertableDataGrid.aspx.vb" Inherits="aspxWeb.InserTableDataGrid"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <asp:DataGrid id="DataGrid1" runat="server" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4" ShowFooter="True" AutoGenerateColumns="False"> <SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"></SelectedItemStyle> <ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle> <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle> <FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle> <Columns> <asp:TemplateColumn HeaderText="Employee ID"> <ItemTemplate> <asp:Label id=Label3 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.employeeid") %>'> </asp:Label> </ItemTemplate> <FooterTemplate> <asp:LinkButton id="LinkButton1" runat="server" CommandName="Insert">Insert</asp:LinkButton> </FooterTemplate> <EditItemTemplate> <asp:TextBox id=TextBox5 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.employeeid") %>'> </asp:TextBox> </EditItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText="Last Name"> <ItemTemplate> <asp:Label id=Label1 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.lastname") %>'> </asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox id="TextBox2" runat="server"></asp:TextBox> </FooterTemplate> <EditItemTemplate> <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> </EditItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText="First Name"> <ItemTemplate> <asp:Label id=Label2 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.firstname") %>'> </asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox id="TextBox4" runat="server"></asp:TextBox> </FooterTemplate> <EditItemTemplate> <asp:TextBox id="TextBox3" runat="server"></asp:TextBox> </EditItemTemplate> </asp:TemplateColumn> </Columns> <PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC"></PagerStyle> </asp:DataGrid> </form> </body> </HTML>

InsertableDataGrid.aspx.vb

Imports System.Data Imports System.Data.SqlClient Public Class InserTableDataGrid Inherits System.Web.UI.Page Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Dim connstr As String = "Integrated Security=SSPI;User ID=sa;Initial Catalog=NorthWind;Data Source=.\netsdk" Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then BindGrid() End If End Sub Sub BindGrid() Dim cnn As New SqlConnection(connstr) Dim da As New SqlDataAdapter("select employeeid,lastname,firstname from employees", cnn) Dim ds As New DataSet() da.Fill(ds, "employees") DataGrid1.DataSource = ds DataGrid1.DataBind() End Sub Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)_ Handles DataGrid1.ItemCommand If e.CommandName = "Insert" Then Dim cnn As New SqlConnection(connstr) Dim t1 As TextBox = e.Item.FindControl("textbox2") Dim t2 As TextBox = e.Item.FindControl("textbox4") cnn.Open() Dim cmd As New SqlCommand("insert into employees(lastname,firstname) values('" & t1.Text & "','" & t2.Text & "')", cnn) cmd.ExecuteNonQuery() cnn.Close() BindGrid() End If End Sub End Class


代码很容易理解,但要声明的是,这是参考孔子的vb版改写的,只是因为有的朋友说用c#不好写。
我才写一个供大家参考。在此,谢谢孔子了。

appe_admin.aspx

<%@ Page language="c#" Codebehind="appe_admin.aspx.cs" AutoEventWireup="false" Inherits="bzh_home.appe_admin" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>appe_admin</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <FONT face="宋体"></FONT>
   <asp:datagrid id="DataGrid1" runat="server" AutoGenerateColumns="False" ShowFooter="True" OnItemCommand="ItemsGrid_Command"
    CellPadding="4" BackColor="White" BorderWidth="1px" BorderStyle="None" BorderColor="#CC9966">
    <SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"></SelectedItemStyle>
    <ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
    <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
    <FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
    <Columns>
     <asp:TemplateColumn HeaderText="Employee ID">
      <ItemTemplate>
       <asp:Label id=Label3 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.编号") %>'>
       </asp:Label>
      </ItemTemplate>
      <FooterTemplate>
       <asp:LinkButton id="LinkButton1" runat="server" CommandName="Insert">Insert</asp:LinkButton>
      </FooterTemplate>
      <EditItemTemplate>
       <asp:TextBox id=TextBox5 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.编号") %>'>
       </asp:TextBox>
      </EditItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText="Last Name">
      <ItemTemplate>
       <asp:Label id=Label1 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.用户名") %>'>
       </asp:Label>
      </ItemTemplate>
      <FooterTemplate>
       <asp:TextBox id="TextBox2" runat="server"></asp:TextBox>
      </FooterTemplate>
      <EditItemTemplate>
       <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
      </EditItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText="First Name">
      <ItemTemplate>
       <asp:Label id=Label2 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.密码") %>'>
       </asp:Label>
      </ItemTemplate>
      <FooterTemplate>
       <asp:TextBox id="TextBox4" runat="server"></asp:TextBox>
      </FooterTemplate>
      <EditItemTemplate>
       <asp:TextBox id="TextBox3" runat="server"></asp:TextBox>
      </EditItemTemplate>
     </asp:TemplateColumn>
    </Columns>
    <PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC"></PagerStyle>
   </asp:datagrid>
  </form>
 </body>
</HTML>
<%@ Page language="c#" Codebehind="appe_admin.aspx.cs" AutoEventWireup="false" Inherits="bzh_home.appe_admin" %>

appe_admin.aspx.cs


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace bzh_home
{
 /// <summary>
 /// appe_admin 的摘要说明。
 /// </summary>
 public class appe_admin : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
 
  string connstr = "user id=sa;data source=\"XIDONGS\\DATAMANAGE\";initial catalog=bzh_data";
       
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!Page.IsPostBack){
              BindGrid();
   }           
       
  }

  private void BindGrid(){
   SqlConnection cnn = new SqlConnection(connstr);
   SqlDataAdapter da = new SqlDataAdapter("select * from admin", cnn);
            DataSet ds = new DataSet();
   da.Fill(ds,"admin");
       
      this.DataGrid1.DataSource = ds;   
            this.DataGrid1.DataBind();  
  
  }
       
  public void ItemsGrid_Command(Object sender, DataGridCommandEventArgs e)
  {
   
   if(e.CommandName == "Insert")
   {
               //this.Page.Response.Write("ss");

     SqlConnection cnn = new SqlConnection(connstr);
    
     TextBox t1 = (TextBox)e.Item.FindControl("textbox2");
                 TextBox t2 = (TextBox)e.Item.FindControl("textbox4");
                 cnn.Open();
        SqlCommand cmd = new SqlCommand("insert into admin(用户名,密码) values('" + t1.Text + "','" + t2.Text + "')", cnn);                
                 cmd.ExecuteNonQuery();
                 cnn.Close();
                 BindGrid();
     
   }
   
   
  }


  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion
 }
}

<%@ Page language="c#" Codebehind="appe_admin.aspx.cs" AutoEventWireup="false" Inherits="bzh_home.appe_admin" %>

本文地址:http://com.8s8s.com/it/it43235.htm