zoukankan      html  css  js  c++  java
  • 一个 NHIBERNATE+GRIDVIEW 添加删除修改的例子

    1. interface (界面)
      aspx:
    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

    <html xmlns="" target="_blank">http://www.w3.org/1999/xhtml"> 
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Button ID="btn_INSERT" runat="server" OnClick="btn_INSERT_Click" Text="INSERT" /><br />
            <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" Font-Names="Arial" Font-Size="9pt" ForeColor="Black" GridLines="Vertical" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False" DataKeyNames="ID" OnRowCancelingEdit="GridView1_RowCancelingEdit">
                <FooterStyle BackColor="#CCCC99" />
                <RowStyle BackColor="#F7F7DE" />
                <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
                <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                <asp:BoundField DataField="UserID" HeaderText="UserID"/>
                <asp:BoundField DataField="Message" HeaderText="Message"/>
                <asp:BoundField DataField="CreateTime" HeaderText="CreateTime" ReadOnly="True"/>
                <asp:CommandField CancelText="CANCEL" UpdateText="UPDATE" EditText="EDIT" DeleteText="DELETE" ShowDeleteButton="True" ShowEditButton="True"/>
                </Columns>
            </asp:GridView>
        
        </div>
        </form>
    </body>
    </html>
     
     
    2. aspx.cs(grid's function)

    using System;
    using System.Data;
    using System.Configuration;
    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;
    using System.Collections;

    public partial class _Default : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetBind();
            }
        }
        private void SetBind()
        {
            CUID.GuestMessageCUID gm = new CUID.GuestMessageCUID();
            this.GridView1.DataSource = gm.GetGuestMessage();
            this.GridView1.DataBind();
        }
        protected void btn_INSERT_Click(object sender, EventArgs e)
        {
            CUID.GuestMessageCUID gm = new CUID.GuestMessageCUID();
            IList list = gm.GetGuestMessage();
            list.Insert(0, new DataEntity.GuestMessage());
            this.GridView1.EditIndex = 0;
            this.GridView1.DataSource = list;
            this.GridView1.DataBind();  
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GridViewRow gvr = this.GridView1.Rows[e.RowIndex];
            object AutoID = this.GridView1.DataKeys[e.RowIndex].Value;
            DataEntity.GuestMessage gmentity = new DataEntity.GuestMessage();
            if (AutoID != null)
            {
                gmentity.Id = AutoID.ToString();
                CUID.GuestMessageCUID gm = new CUID.GuestMessageCUID();
                gm.DeleteGuestMessage(gmentity);
                SetBind();
            }
           
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.GridView1.EditIndex = e.NewEditIndex;
            SetBind();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            CUID.GuestMessageCUID gm = new CUID.GuestMessageCUID();
            GridViewRow gvr = this.GridView1.Rows[e.RowIndex];
            TextBox tbUserID = gvr.Cells[0].Controls[0] as TextBox;
            TextBox tbMessage = gvr.Cells[1].Controls[0] as TextBox;
            object AutoID = this.GridView1.DataKeys[e.RowIndex].Value;
            DataEntity.GuestMessage gmentity = new DataEntity.GuestMessage();
            gmentity.UserID = tbUserID.Text;
            gmentity.Message = tbMessage.Text;
            if (AutoID == null)
            {
                gmentity.CreateTime = DateTime.Now;
                gm.AddGuestMessage(gmentity);
            }
            else
            {
                gmentity.Id = AutoID.ToString();
                gmentity.CreateTime = DateTime.Parse(gvr.Cells[2].Text);
                gm.UpdateGuestMessage(gmentity);
            }
            this.GridView1.EditIndex = -1;
            SetBind();
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.GridView1.EditIndex = -1;
            SetBind();
        }
    }
     
    3.cuid.cs (感觉可以和4合并,business layer)
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using DataHelper;
    using System.Data;

    namespace CUID
    {
        public class GuestMessageCUID
        {
            private EntityControl control;

            public GuestMessageCUID()
            {
                control = EntityControl.CreateEntityControl("DataEntity");
            }

            public IList GetGuestMessage()
            {
                return control.GetEntities("from DataEntity.GuestMessage");
            }

            public void AddGuestMessage(DataEntity.GuestMessage gm)
            {
                control.AddEntity(gm);
            }

            public void UpdateGuestMessage(DataEntity.GuestMessage gm)
            {
                control.UpdateEntity(gm,gm.Id);
            }

            public void DeleteGuestMessage(DataEntity.GuestMessage gm)
            {
                control.DeleteEntity(gm);
            }
        }
    }


    4.datahelper.cs (即通常的business logic layer吧)
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using NHibernate;
    using NHibernate.Cfg;
    using System.Data;

    namespace DataHelper
    {
        public class SessionFactory
        {
            private static ISessionFactory sessions;
            private static Configuration cfg;
            static readonly object padlock = new object();
            public static ISession OpenSession(string AssemblyName)
            {
                if (sessions == null)
                {
                    lock (padlock)
                    {
                        if (sessions == null)
                        {
                            BuildSessionFactory(AssemblyName);
                        }
                    }
                }
                return sessions.OpenSession();
            }

            private static void BuildSessionFactory(string AssemblyName)
            {
                cfg = new Configuration();
                cfg.AddAssembly(AssemblyName);
                sessions = cfg.BuildSessionFactory();
            }
        }

        public class EntityControl
        {
            private static EntityControl entity;
            private string _AssemblyName;
            static readonly object padlock = new object();
            public static EntityControl CreateEntityControl(string AssemblyName)
            {
                if (entity == null)
                {
                    lock (padlock)
                    {
                        if (entity == null)
                        {
                            entity = new EntityControl();
                            entity._AssemblyName = AssemblyName;
                        }
                    }
                }
                return entity;

            }

            public void AddEntity(Object entity)
            {
                ISession session = SessionFactory.OpenSession(_AssemblyName);
                ITransaction transaction = session.BeginTransaction();
                try
                {
                    session.Save(entity);
                    transaction.Commit();
                }

                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
                finally
                {
                    session.Close();
                }
            }

            public void UpdateEntity(Object entity ,Object key)
            {
                ISession session = SessionFactory.OpenSession(_AssemblyName);
                ITransaction transaction = session.BeginTransaction();
                try
                {
                    session.Update(entity);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
                finally
                {
                    session.Close();
                }
            }

            public void DeleteEntity(object entity)
            {
                ISession session = SessionFactory.OpenSession(_AssemblyName);
                ITransaction transaction = session.BeginTransaction();
                try
                {
                    session.Delete(entity);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
                finally
                {
                    session.Close();
                }
            }

            public IList GetEntities(string strHQL)
            {
                IList list;
                ISession session = SessionFactory.OpenSession(_AssemblyName);
                list = session.Find(strHQL);
                session.Close();
                return list;
            }
        }
    }
     
    5.实体 (即Nhibernate与数据库间的映射)
    using System;
    using System.Collections;

    namespace DataEntity
    {
        #region GuestMessage

        /// <summary>
        /// GuestMessage object for NHibernate mapped table 'GuestMessage'.
        /// </summary>
        public class GuestMessage
        {
            #region Member Variables
            
            protected string _id;
            protected string _userID;
            protected string _message;
            protected DateTime _createTime;

            #endregion

            #region Constructors

            public GuestMessage() { }

            public GuestMessage( string userID, string message, DateTime createTime )
            {
                this._userID = userID;
                this._message = message;
                this._createTime = createTime;
            }

            #endregion

            #region Public Properties

            public string Id
            {
                get {return _id;}
                set
                {
                    if ( value != null && value.Length > 50)
                        throw new ArgumentOutOfRangeException("Invalid value for Id", value, value.ToString());
                    _id = value;
                }
            }

            public string UserID
            {
                get { return _userID; }
                set
                {
                    if ( value != null && value.Length > 50)
                        throw new ArgumentOutOfRangeException("Invalid value for UserID", value, value.ToString());
                    _userID = value;
                }
            }

            public string Message
            {
                get { return _message; }
                set
                {
                    if ( value != null && value.Length > 16)
                        throw new ArgumentOutOfRangeException("Invalid value for Message", value, value.ToString());
                    _message = value;
                }
            }

            public DateTime CreateTime
            {
                get { return _createTime; }
                set { _createTime = value; }
            }

            

            #endregion
        }
        #endregion
    }
     
    6.实体xml (即nhibernate的app.config)
    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:NHibernate-mapping-2.0">
        <class name="DataEntity.GuestMessage, DataEntity" table="GuestMessage">
            <id name="Id" type="String" unsaved-value="null">
                <column name="AutoID" length="50" sql-type="varchar" not-null="true" unique="true" index="PK_Message"/>
                <generator class="identity" />
            </id>
            <property name="UserID" type="String">
                <column name="UserID" length="50" sql-type="varchar" not-null="false"/>
            </property>
            <property name="Message" type="String">
                <column name="Message" length="16" sql-type="text" not-null="false"/>
            </property>
            <property name="CreateTime" type="DateTime">
                <column name="CreateTime" length="8" sql-type="datetime" not-null="false"/>
            </property>
        </class>
    </hibernate-mapping>
  • 相关阅读:
    ubuntu 14.04 LTS 163更新源
    Windows 2008R2 修改SID
    ubuntu14 使用rsync远程备份文件
    vim常用
    Ubuntu创建lvm
    Windows 迁移本地用户配置文件到域用户
    Linux scp使用
    Centos 7 修改网卡名称、静态IP
    Axel多线程工具安装
    testlink 1.9.19安装
  • 原文地址:https://www.cnblogs.com/craig/p/1267597.html
Copyright © 2011-2022 走看看