可编辑的 DataGrid 实例

数据库在文件中名为jsp

<%@ Page language="c#" Codebehind="WebForm2.aspx.cs" AutoEventWireup="false" Inherits="aspnet1.WebForm2" %>
<HTML>
 <HEAD>
 </HEAD>
 <BODY>
  <h2>可编辑的&nbsp;DataGrid
  </h2>
  <hr SIZE="1">
  <form id="Form1" runat="server">
   <asp:datagrid id="dgUserInfo" runat="server" OnSelectedIndexChanged="dgUserInfo_SelectedIndexChanged"
    width="360px" CellPadding="4" BackColor="White" PageSize="6" AllowPaging="True" OnDeleteCommand="DataGrid_Delete"
    OnCancelCommand="DataGrid_Cancel" OnUpdateCommand="DataGrid_Update" OnEditCommand="DataGrid_Edit"
    OnItemCommand="DataGrid_ItemCommand" DataKeyField="au_id" OnPageIndexChanged="DataGrid_Page"
    AutoGenerateColumns="False" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" Height="120px">
    <SelectedItemStyle Font-Bold="True" ForeColor="#CCFF99" BackColor="#009999"></SelectedItemStyle>
    <ItemStyle ForeColor="#003399" BackColor="White"></ItemStyle>
    <HeaderStyle Font-Bold="True" ForeColor="#CCCCFF" BackColor="#003399"></HeaderStyle>
    <FooterStyle ForeColor="#003399" BackColor="#99CCCC"></FooterStyle>
    <Columns>
     <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" HeaderText="Edit" CancelText="Cancel"
      EditText="Edit">
      <ItemStyle Font-Size="Smaller" Width="10%"></ItemStyle>
     </asp:EditCommandColumn>
     <asp:ButtonColumn Text="Delete" HeaderText="Del" CommandName="Delete">
      <ItemStyle Font-Size="Smaller" Width="10%"></ItemStyle>
     </asp:ButtonColumn>
     <asp:BoundColumn DataField="au_id" SortExpression="au_id" HeaderText="id号">
      <ItemStyle Wrap="False"></ItemStyle>
     </asp:BoundColumn>
     <asp:BoundColumn DataField="au_lname" SortExpression="au_lname" HeaderText="密码">
      <ItemStyle Wrap="False"></ItemStyle>
     </asp:BoundColumn>
     <asp:BoundColumn DataField="au_fname" SortExpression="au_fname" HeaderText="姓名">
      <ItemStyle Wrap="False"></ItemStyle>
     </asp:BoundColumn>
    </Columns>
    <PagerStyle Font-Size="Smaller" HorizontalAlign="Left" ForeColor="#003399" BackColor="#99CCCC"
     Mode="NumericPages"></PagerStyle>
   </asp:datagrid>
   <P><FONT face="宋体"></FONT>    
    <asp:linkbutton id="LinkButton1" οnclick="AddNew_Click" runat="server" Font-Size="smaller" Text="Add new item"></asp:linkbutton><br>
    <asp:label id="Message" runat="server" width="80%" enableviewstate="false" forecolor="red"></asp:label></P>
   <P>&nbsp;</P>
   <P><FONT face="宋体"></FONT>&nbsp;</P>
   <P>&nbsp;</P>
  </form>
  
 </BODY>
</HTML>


--------------------------------------------------------------------------------------------------------------------------------

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 aspnet1
{
 /// <summary>
 /// WebForm2 的摘要说明。
 /// </summary>
 public class WebForm2 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid dgUserInfo;
  protected System.Web.UI.WebControls.LinkButton LinkButton1;
  protected System.Web.UI.WebControls.Label Message;
  
  
  // 在此处放置用户代码以初始化页面
   
  string ConnectionString = "server=localhost;database=jsp;uid=sa";//
  //string ConnectionString =data.constr;//直接调用类data的方法constr 
  string SelectCommand = "SELECT au_id, au_lname, au_fname from aspnet order by id desc";
   
  bool isEditing = false;
   
  protected void Page_Load(object sender, EventArgs e)
  {
   
   if (!Page.IsPostBack)
   {
   
    // Databind the data grid on the first request only
    // (on postback, bind only in editing, paging and sorting commands)
       
    BindGrid();
    
   }
  }
  

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

  }
  #endregion

  protected void dgUserInfo_SelectedIndexChanged(object sender, System.EventArgs e)
  {

  }
  
  protected void DataGrid_ItemCommand(object sender, DataGridCommandEventArgs e)
  {
   
   // this event fires prior to all of the other commands
   // use it to provide a more graceful transition out of edit mode
   
   CheckIsEditing(e.CommandName);
  }
   
  protected  void CheckIsEditing(string commandName)
  {
   
   if (dgUserInfo.EditItemIndex != -1)
   {
   
    // we are currently editing a row
    if (commandName != "Cancel" && commandName != "Update")
    {
   
     // user's edit changes (if any) will not be committed
     Message.Text = "抱歉,你还没保存数据或者你按取消后再执行刚才的操作!";
     isEditing = true;
    }
   }
  }
   
  protected void DataGrid_Edit(object sender, DataGridCommandEventArgs e)
  {
   
   // turn on editing for the selected row
   
   if (!isEditing)
   {
    dgUserInfo.EditItemIndex = e.Item.ItemIndex;
    BindGrid();
   }
  }
   
  protected    void DataGrid_Update(object sender, DataGridCommandEventArgs e)
  {
   
   // update the database with the new values
   
   // get the edit text boxes
   string id = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
   string lname = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
   string fname = ((TextBox)e.Item.Cells[4].Controls[0]).Text;
   
   // TODO: update the Command value for your application
   SqlConnection myConnection = new SqlConnection(ConnectionString);
   SqlCommand UpdateCommand = new SqlCommand();
   UpdateCommand.Connection = myConnection;
   
   if (AddingNew)
    UpdateCommand.CommandText = "INSERT INTO aspnet(au_id, au_lname, au_fname, contract) VALUES (@au_id, @au_lname, @au_fname, 0)";
   else
    UpdateCommand.CommandText = "UPDATE aspnet SET au_lname = @au_lname, au_fname = @au_fname WHERE au_id = @au_id";
   
   UpdateCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11).Value = id;
   UpdateCommand.Parameters.Add("@au_lname", SqlDbType.VarChar, 40).Value = lname;
   UpdateCommand.Parameters.Add("@au_fname", SqlDbType.VarChar, 20).Value = fname;
   
   // execute the command
   try
   {
    myConnection.Open();
    UpdateCommand.ExecuteNonQuery();
   }
   catch (Exception ex)
   {
    Message.Text = ex.ToString();
   }
   finally
   {
    myConnection.Close();
   }
   
   // Resort the grid for new records
   if (AddingNew)
   {
   
    dgUserInfo.CurrentPageIndex = 0;
    AddingNew = false;
   }
   
   // rebind the grid
   dgUserInfo.EditItemIndex = -1;
   BindGrid();
  }
   
  protected   void DataGrid_Cancel(object sender, DataGridCommandEventArgs e)
  {
   
   // cancel editing
   
   dgUserInfo.EditItemIndex = -1;
   BindGrid();
   
   AddingNew = false;
  }
   
  protected   void DataGrid_Delete(object sender, DataGridCommandEventArgs e)
  {
   
   // delete the selected row
   
   if (!isEditing)
   {
   
    // the key value for this row is in the DataKeys collection
    string keyValue = (string)dgUserInfo.DataKeys[e.Item.ItemIndex];
   
    // TODO: update the Command value for your application
    SqlConnection myConnection = new SqlConnection(ConnectionString);
    SqlCommand DeleteCommand = new SqlCommand("DELETE from aspnet where au_id='" + keyValue + "'", myConnection);
   
    // execute the command
    myConnection.Open();
    DeleteCommand.ExecuteNonQuery();
    myConnection.Close();
   
    // rebind the grid
    dgUserInfo.CurrentPageIndex = 0;
    dgUserInfo.EditItemIndex = -1;
    BindGrid();
   }
  }
   
  protected  void DataGrid_Page(object sender, DataGridPageChangedEventArgs e)
  {
   
   // display a new page of data
   
   if (!isEditing)
   {
    dgUserInfo.EditItemIndex = -1;
    dgUserInfo.CurrentPageIndex = e.NewPageIndex;
    BindGrid();
   }
  }
   
  protected   void AddNew_Click(Object sender, EventArgs e)
  {
   
   // add a new row to the end of the data, and set editing mode 'on'
   
   CheckIsEditing("");
   
   if (!isEditing)
   {
   
    // set the flag so we know to do an insert at Update time
    AddingNew = true;
   
    // add new row to the end of the dataset after binding
   
    // first get the data
    SqlConnection myConnection = new SqlConnection(ConnectionString);
    SqlDataAdapter myCommand = new SqlDataAdapter(SelectCommand, myConnection);
   
    DataSet ds = new DataSet();
    myCommand.Fill(ds);
   
    // add a new blank row to the end of the data
    object[] rowValues = { "", "", "" };
    ds.Tables[0].Rows.Add(rowValues);
   
    // figure out the EditItemIndex, last record on last page
    int recordCount = ds.Tables[0].Rows.Count;
    if (recordCount > 1)
     recordCount--;
    dgUserInfo.CurrentPageIndex = recordCount/dgUserInfo.PageSize;
    dgUserInfo.EditItemIndex = recordCount%dgUserInfo.PageSize;
   
    // databind
    dgUserInfo.DataSource = ds;
    dgUserInfo.DataBind();
   }
  }
   
  // ---------------------------------------------------------------
  //
  // Helpers Methods:
  //
   
  // property to keep track of whether we are adding a new record,
  // and save it in viewstate between postbacks
   
  protected bool AddingNew
  {
   
   get
   {
    object o = ViewState["AddingNew"];
    return (o == null) ? false : (bool)o;
   }
   set
   {
    ViewState["AddingNew"] = value;
   }
  }
   
  protected   void BindGrid()
  {
   
   SqlConnection myConnection = new SqlConnection(ConnectionString);
   SqlDataAdapter myCommand = new SqlDataAdapter(SelectCommand, myConnection);
   
   DataSet ds = new DataSet();
   myCommand.Fill(ds);
   
   dgUserInfo.DataSource = ds;
   dgUserInfo.DataBind();
  }

  private void LinkButton1_Click(object sender, System.EventArgs e)
  {
  
  }
   
   
 }
}

转载于:https://www.cnblogs.com/battler/archive/2005/05/12/153729.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值