一个 NHIBERNATE+GRIDVIEW 添加删除修改的例子(单表)
点击这里下载
aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>无标题页</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>
<!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>无标题页</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>
aspx.cs
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();
}
}
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();
}
}
cuid.cs
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);
}
}
}
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);
}
}
}
datahelper.cs
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;
}
}
}
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;
}
}
}
实体
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
}
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
}
实体xml
<?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>
<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>
欢迎大家阅读我的极客时间专栏《Java业务开发常见错误100例》【全面避坑+最佳实践=健壮代码】