可編輯的 DataGrid 執行個體

來源:互聯網
上載者:User

資料庫在檔案中名為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" onclick="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 Form設計器產生的程式碼

  override protected void OnInit(EventArgs e)

  {

   //

   // CODEGEN: 該調用是 ASP.NET Web Form設計器所必需的。

   //

   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)

  {

  

  }

   

   

 }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.