MyBatis.Net使用入门(三)

    • 项目结构如下
    • Bookcs模型
    • Bookxml映射配置文件
    • 日志配置文件log4netxml
    • 数据库提供程序配置providersconfig
    • Mybatis全局配置文件SqlMapconfig
    • Programcs的入口程序
    • frmBookDetail窗体后台代码
    • frmBookView窗体后台代码
    • 运行结果如图
        • 搜索结果
        • 查看详细
        • 更新数据
        • 删除数据
        • 其他相关文章

项目结构如下:

MyBatis.Net使用入门(三)_第1张图片


Book.cs模型:

 public class Book
    {
        private string _Isbn;
        private string _Title;
        private DateTime _SaleDate;
        private int _Price;
        public string Isbn
        {
            get { return _Isbn; }
            set
            {
                if (value.Length != 10)
                {
                    throw new DomainException("ISBN是无效的。");
                }
                _Isbn = value;
            }
        }

        public string IsbnWithHyphen
        {
            get
            {
                return
                    _Isbn.Substring(0, 1) + "-" + _Isbn.Substring(1, 4) + "-" + _Isbn.Substring(5, 4) + "-" +
                    _Isbn.Substring(9, 1);
            }
        }

        public string Title
        {
            get { return _Title; }
            set
            {
                if (value == "")
                {
                    throw new DomainException("标题是无效的。");
                }

                _Title = value;
            }
        }

        public DateTime SaleDate
        {
            get { return _SaleDate; }
            set
            {
                if (DateTime.Compare(value.Date, DateTime.Now) > 0)
                {
                    throw new DomainException("发布日期是无效的。");
                }
                _SaleDate = value;
            }
        }

        public int Price
        {
            get { return _Price; }
            set
            {
                if (value <= 0)
                {
                    throw new DomainException("价格是无效的。");
                }
                _Price = value;
            }
        }
    }

Book.xml映射配置文件:


<sqlMap namespace="Book" xmlns="http://ibatis.apache.org/mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">


  
  
  <alias>
        <typeAlias alias="Book" type="MybatisDemo.Domain.Books.Book,MybatisDemo" />
    alias>

    <resultMaps>
        <resultMap id="BookResult" class="Book">
            <result property="Isbn" column="ISBN" />
            <result property="Title" column="TITLE" />
            <result property="SaleDate" column="SALE_DATE" />
            <result property="Price" column="PRICE" />
        resultMap>
    resultMaps>

    <statements>
        
        <insert id="InsertBook" parameterClass="Book">
            insert into BOOK
                (ISBN,TITLE,SALE_DATE,PRICE)
            values 
                (#Isbn#, #Title#, #SaleDate#,#Price#)
        insert>


        
        <update id="UpdateBook" parameterClass="Book">
            update BOOK 
            set TITLE = #Title#,
            SALE_DATE = #SaleDate#, 
            PRICE = #Price#
            where ISBN = #Isbn#
        update>

        
        <delete id="DeleteBook" parameterClass="System.Int32">
            delete from BOOK
            where ISBN = #value#
        delete>


        


        
        <select id="GetBookByIsbn" resultClass="Book" parameterClass="System.String">
            select
                ISBN as Isbn,
                TITLE as Title,
                SALE_DATE as SaleDate,
                PRICE as Price
            from BOOK
            where ISBN = #Isbn#
        select>       

             


        <select id="GetBookList" resultMap="BookResult">
            select
                ISBN,
                TITLE,
                SALE_DATE,
                PRICE
            from BOOK
        select>   

        <select id="GetBookListByTitle" extends="GetBookList" resultMap="BookResult" parameterClass="System.String">
            where TITLE LIKE '%$VALUE$%'
            order by ISBN
        select>

        <select id="GetBookListByPrice" extends="GetBookList" resultMap="BookResult" parameterClass="System.Collections.Hashtable">
            <dynamic prepend="where">
                <isEqual property="priceCompare" compareValue="以上">
                = #price#
                ]]>
                isEqual>
                <isEqual property="priceCompare" compareValue="以下">
                
                isEqual>
            dynamic>
            order by PRICE
        select>
    statements>
sqlMap>

日志配置文件log4net.xml

 

<configuration>
    <configSections>
        <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
    configSections>
    <appSettings>
        <add key="log4net.Internal.Debug" value="true"/>
    appSettings>


    <log4net>
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c %M [%x] - %m%n" />
            layout>
        appender>

        <appender name="FileAppender" type="log4net.Appender.FileAppender">
            <param name="File" value="Fileサンプル.log" />
            <param name="AppendToFile" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
            layout>
        appender>

        <appender name="RollingFileAppender_DateTime" type="log4net.Appender.RollingFileAppender">

            <param name="File" value="MybatisDemo.log" />

            <param name="AppendToFile" value="true" />

            <param name="RollingStyle" value="Date" />
            
            
            
            
            
            
            <param name="StaticLogFileName" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
            layout>
        appender>     


        <appender name="RollingFileAppender_Size" type="log4net.Appender.RollingFileAppender">

            <param name="File" value="iBatisSampleサイズ.log" />

            <param name="AppendToFile" value="true" />

            <param name="RollingStyle" value="Size" />

            <param name="MaximumFileSize" value="20KB" />
            
            
            <param name="MaxSizeRollBackups" value="5" />       
            <param name="StaticLogFileName" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
            layout>
        appender>



        <appender name="RollingFileAppender_Composite" type="log4net.Appender.RollingFileAppender">

            <param name="File" value="iBatis大小及日期.log" />

            <param name="AppendToFile" value="true" />
            <param name="RollingStyle" value="Composite" />
            <param name="DatePattern" value="yyyy-MM-dd-HH-mm" />
            <param name="MaximumFileSize" value="5KB" />
            <param name="MaxSizeRollBackups" value="5" />           
            <param name="StaticLogFileName" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
            layout>
        appender>


        <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
            <applicationName value="MyApp" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
            layout>
        appender>

        <appender name="SmtpAppender" type="log4net.Appender.SMTPAppender">
            <param name="To" value="[email protected]" />
            <param name="From" value="[email protected]" />
            <param name="Subject" value="[${COMPUTERNAME}] log4net的系统错误通知" /> 
            <param name="SMTPHost" value="smtp.xxx.msn.wings.to" />
            <param name="LocationInfo" value="false" />
            <param name="BufferSize" value="1024" />
            <param name="Lossy" value="true" />
            <evaluator type="log4net.spi.LevelEvaluator">
                <param name="Threshold" value="FATAL"/>
            evaluator>
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="此邮件是由log4net的自动发送。\r\n\r\n" />
                <param name="Footer" value="\r\n并尽快请证实。\r\n" />             
                <param name="ConversionPattern" value="%-5p %d{yyyy/MM/dd HH:mm} [%c] %m%n" />
            layout>
        appender>

        <appender name="NetSendAppender" type="log4net.Appender.NetSendAppender">
            <threshold value="FATAL" />
            <server value="FROM_PC" />
            <recipient value="TO_PC" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
            layout>
        appender>

        <appender name="UdpAppender" type="log4net.Appender.UdpAppender">
            <remoteAddress value="127.0.0.1" />
            <remotePort value="8080" />
            <layout type="log4net.Layout.XmlLayoutSchemaLog4j">
                <locationInfo value="true" />
            layout>
        appender>


        <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
            <connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=LogDb.mdb;User Id=;Password=;" />
            <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
            <parameter>
                <parameterName value="@log_date" />
                <dbType value="String" />
                <size value="25" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%d" />
                layout>
            parameter>
            <parameter>
                <parameterName value="@thread" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%t" />
                layout>
            parameter>
            <parameter>
                <parameterName value="@log_level" />
                <dbType value="String" />
                <size value="5" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%p" />
                layout>
            parameter>
            <parameter>
                <parameterName value="@logger" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%c" />
                layout>
            parameter>
            <parameter>
                <parameterName value="@message" />
                <dbType value="String" />
                <size value="1024" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%m" />
                layout>
            parameter>
        appender>

        <root>
            <level value="ERROR" />
            <appender-ref ref="ConsoleAppender" />
            <appender-ref ref="RollingFileAppender_DateTime" />
        root>


        <logger name="MybatisDemo">
            <level value="DEBUG" />
        logger>

        <logger name="IBatisNet.DataMapper.Commands.DefaultPreparedCommand">
            <level value="DEBUG" />
        logger>
        <logger name="IBatisNet.DataMapper.Configuration.Cache.CacheModel">
            <level value="DEBUG" />
        logger>
        <logger name="IBatisNet.DataMapper.LazyLoadList">
            <level value="DEBUG" />
        logger>
        <logger name="IBatisNet.DataMapper.SqlMapSession">
            <level value="DEBUG" />
        logger>
        <logger name="IBatisNet.Common.Transaction.TransactionScope">
            <level value="DEBUG" />
        logger>
        <logger name="IBatisNet.DataMapper.Configuration.Statements.PreparedStatementFactory">
            <level value="OFF" />
        logger>
        <logger name="IBatisNet.DataMapper.Commands.IPreparedCommand">
            <level value="OFF" />
        logger>  

    log4net>
configuration>

数据库提供程序配置providers.config



<providers xmlns="http://ibatis.apache.org/providers" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <clear />
  <provider
    name="sqlServer1.1"
    description="Microsoft SQL Server 7.0/2000, provider V1.0.5000.0 in framework .NET V1.1"
    default="true"
    assemblyName="System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    connectionClass="System.Data.SqlClient.SqlConnection"
    commandClass="System.Data.SqlClient.SqlCommand"
    parameterClass="System.Data.SqlClient.SqlParameter"
    parameterDbTypeClass="System.Data.SqlDbType"
    parameterDbTypeProperty="SqlDbType"
    dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"
    commandBuilderClass="System.Data.SqlClient.SqlCommandBuilder"
    usePositionalParameters="false"
    useParameterPrefixInSql="true"
    useParameterPrefixInParameter="true"
    parameterPrefix="@" />
  <provider
    name="sqlServer2.0"
    enabled="true"
    description="Microsoft SQL Server, provider V2.0.0.0 in framework .NET V2.0"
    assemblyName="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    connectionClass="System.Data.SqlClient.SqlConnection"
    commandClass="System.Data.SqlClient.SqlCommand"
    parameterClass="System.Data.SqlClient.SqlParameter"
    parameterDbTypeClass="System.Data.SqlDbType"
    parameterDbTypeProperty="SqlDbType"
    dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"
    commandBuilderClass=" System.Data.SqlClient.SqlCommandBuilder"
    usePositionalParameters="false"
    useParameterPrefixInSql="true"
    useParameterPrefixInParameter="true"
    parameterPrefix="@"
    allowMARS="false" />
  <provider
    name="OleDb1.1"
    description="OleDb, provider V1.0.5000.0 in framework .NET V1.1"
    enabled="true"
    assemblyName="System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    connectionClass="System.Data.OleDb.OleDbConnection"
    commandClass="System.Data.OleDb.OleDbCommand"
    parameterClass="System.Data.OleDb.OleDbParameter"
    parameterDbTypeClass="System.Data.OleDb.OleDbType"
    parameterDbTypeProperty="OleDbType"
    dataAdapterClass="System.Data.OleDb.OleDbDataAdapter"
    commandBuilderClass="System.Data.OleDb.OleDbCommandBuilder"
    usePositionalParameters="true"
    useParameterPrefixInSql="false"
    useParameterPrefixInParameter="false"
    parameterPrefix="" />
  <provider
    name="Odbc1.1"
    description="Odbc, provider V1.0.5000.0 in framework .NET V1.1"
    enabled="true"
    assemblyName="System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    connectionClass="System.Data.Odbc.OdbcConnection"
    commandClass="System.Data.Odbc.OdbcCommand"
    parameterClass="System.Data.Odbc.OdbcParameter"
    parameterDbTypeClass="System.Data.Odbc.OdbcType"
    parameterDbTypeProperty="OdbcType"
    dataAdapterClass="System.Data.Odbc.OdbcDataAdapter"
    commandBuilderClass="System.Data.Odbc.OdbcCommandBuilder"
    usePositionalParameters="true"
    useParameterPrefixInSql="false"
    useParameterPrefixInParameter="false"
    parameterPrefix="@" />
  <provider
    name="oracle9.2"
    description="Oracle, Oracle provider V9.2.0.401"
    enabled="false"
    assemblyName="Oracle.DataAccess, Version=9.2.0.401, Culture=neutral, PublicKeyToken=89b483f429c47342"
    connectionClass="Oracle.DataAccess.Client.OracleConnection"
    commandClass="Oracle.DataAccess.Client.OracleCommand"
    parameterClass="Oracle.DataAccess.Client.OracleParameter"
    parameterDbTypeClass="Oracle.DataAccess.Client.OracleDbType"
    parameterDbTypeProperty="OracleDbType"
    dataAdapterClass="Oracle.DataAccess.Client.OracleDataAdapter"
    commandBuilderClass="Oracle.DataAccess.Client.OracleCommandBuilder"
    usePositionalParameters="false"
    useParameterPrefixInSql="true"
    useParameterPrefixInParameter="false"
    parameterPrefix=":"
    useDeriveParameters="false" />
  <provider
    name="oracle10.1"
    description="Oracle, oracle provider V10.1.0.301"
    enabled="false"
    assemblyName="Oracle.DataAccess, Version=10.1.0.301, Culture=neutral, PublicKeyToken=89b483f429c47342"
    connectionClass="Oracle.DataAccess.Client.OracleConnection"
    commandClass="Oracle.DataAccess.Client.OracleCommand"
    parameterClass="Oracle.DataAccess.Client.OracleParameter"
    parameterDbTypeClass="Oracle.DataAccess.Client.OracleDbType"
    parameterDbTypeProperty="OracleDbType"
    dataAdapterClass="Oracle.DataAccess.Client.OracleDataAdapter"
    commandBuilderClass="Oracle.DataAccess.Client.OracleCommandBuilder"
    usePositionalParameters="true"
    useParameterPrefixInSql="true"
    useParameterPrefixInParameter="true"
    parameterPrefix=":"
    useDeriveParameters="false" />
  <provider
    name="MySql"
    description="MySQL, MySQL provider V1.0.4.20163"
    enabled="false"
    assemblyName="MySql.Data, Version=1.0.4.20163, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
    connectionClass="MySql.Data.MySqlClient.MySqlConnection"
    commandClass="MySql.Data.MySqlClient.MySqlCommand"
    parameterClass="MySql.Data.MySqlClient.MySqlParameter"
    parameterDbTypeClass="MySql.Data.MySqlClient.MySqlDbType"
    parameterDbTypeProperty="MySqlDbType"
    dataAdapterClass="MySql.Data.MySqlClient.MySqlDataAdapter"
    commandBuilderClass="MySql.Data.MySqlClient.MySqlCommandBuilder"
    usePositionalParameters="false"
    useParameterPrefixInSql="true"
    useParameterPrefixInParameter="true"
    parameterPrefix="@" />
  <provider
    name="SQLite3"
    description="SQLite, SQLite.NET provider V0.21.1869.3794"
    enabled="false"
    assemblyName="SQLite.NET, Version=0.21.1869.3794, Culture=neutral, PublicKeyToken=c273bd375e695f9c"
    connectionClass="Finisar.SQLite.SQLiteConnection"
    commandClass="Finisar.SQLite.SQLiteCommand"
    parameterClass="Finisar.SQLite.SQLiteParameter"
    parameterDbTypeClass="System.Data.DbType, System.Data"
    parameterDbTypeProperty="DbType"
    dataAdapterClass="Finisar.SQLite.SQLiteDataAdapter"
    commandBuilderClass="Finisar.SQLite.SQLiteCommandBuilder"
    usePositionalParameters="true"
    useParameterPrefixInSql="false"
    useParameterPrefixInParameter="false"
    parameterPrefix=""
    setDbParameterPrecision="false"
    setDbParameterScale="false"
    setDbParameterSize="false" />
  <provider
    name="PostgreSql0.7"
    description="PostgreSql, Npgsql provider V0.7.0.0"
    enabled="false"
    assemblyName="Npgsql, Version=0.7.0.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"
    connectionClass="Npgsql.NpgsqlConnection"
    commandClass="Npgsql.NpgsqlCommand"
    parameterClass="Npgsql.NpgsqlParameter"
    parameterDbTypeClass="NpgsqlTypes.NpgsqlDbType"
    parameterDbTypeProperty="NpgsqlDbType"
    dataAdapterClass="Npgsql.NpgsqlDataAdapter"
    commandBuilderClass="Npgsql.NpgsqlCommandBuilder"
    usePositionalParameters="false"
    useParameterPrefixInSql="true"
    useParameterPrefixInParameter="true"
    parameterPrefix=":" />
providers>

Mybatis全局配置文件SqlMap.config:


<sqlMapConfig xmlns="http://ibatis.apache.org/dataMapper"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  
  
  
  <settings>
    <setting useStatementNamespaces="false" />
    <setting cacheModelsEnabled="true" />
  settings>

  <providers resource="../../Resources/providers.config" />
  <database>
    
    
    <provider name="sqlServer2.0" />
    <dataSource name="SQLServer"
                connectionString="Data Source=.\SQLINSTANCE;Initial Catalog=MyBatisDemo;Persist Security Info=True;User ID=sa;Password=123456;connection lifetime=5; min pool size=1; max pool size=50" />
  database>

  
  <sqlMaps>
    <sqlMap resource="../../Resources/Maps/Book.xml" />
    
  sqlMaps>
sqlMapConfig>

Program.cs的入口程序:

 internal static class Program
    {
        private static readonly log4net.ILog _logger =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        /// 
        /// 应用程序的主入口点。
        /// 
        [STAThread]
        private static void Main()
        {
            try
            {
                _logger.Info("●启动iBATIS.NET");
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmBookView());
            }
            catch (Exception ex)
            {
                _logger.Error("★iBATIS.NET示例应用程序错误★", ex);
                MessageBox.Show("一个意外的错误,并退出应用程序。\r了解更多信息,查看“log4net的”的日志。",
                    "iBatisSample", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            _logger.Info("●退出iBATIS.NET");
        }
    }

frmBookDetail窗体后台代码:

 public class frmBookDetail : System.Windows.Forms.Form
    {
        //获取log4net的实例
        private static readonly log4net.ILog _logger =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static string baseDir = Path.GetFullPath(@"../../");
        private static DomSqlMapBuilder builder = new DomSqlMapBuilder();
        private static ISqlMapper mapper = builder.Configure(baseDir + @"Resources\SqlMap.config");


        private string _userIsbn = null;
        private String _crudStatus = null;
        private System.Windows.Forms.Label lblIsbn;
        private System.Windows.Forms.Label lblTitle;
        private System.Windows.Forms.Label lblSaleDate;
        private System.Windows.Forms.Label lblPrice;
        private System.Windows.Forms.TextBox txtPrice;
        private System.Windows.Forms.Button btnCancel;
        private System.Windows.Forms.TextBox txtIsbn;
        private System.Windows.Forms.TextBox txtTitle;
        private System.Windows.Forms.DateTimePicker dtpBirthday;
        private System.Windows.Forms.Button btnOk;

        private System.ComponentModel.Container components = null;

        public frmBookDetail()
        {
            InitializeComponent();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.txtIsbn = new System.Windows.Forms.TextBox();
            this.txtTitle = new System.Windows.Forms.TextBox();
            this.dtpBirthday = new System.Windows.Forms.DateTimePicker();
            this.txtPrice = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblIsbn = new System.Windows.Forms.Label();
            this.lblTitle = new System.Windows.Forms.Label();
            this.lblSaleDate = new System.Windows.Forms.Label();
            this.lblPrice = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // txtIsbn
            // 
            this.txtIsbn.Location = new System.Drawing.Point(147, 24);
            this.txtIsbn.MaxLength = 10;
            this.txtIsbn.Name = "txtIsbn";
            this.txtIsbn.Size = new System.Drawing.Size(115, 25);
            this.txtIsbn.TabIndex = 1;
            // 
            // txtTitle
            // 
            this.txtTitle.Location = new System.Drawing.Point(147, 68);
            this.txtTitle.MaxLength = 50;
            this.txtTitle.Name = "txtTitle";
            this.txtTitle.Size = new System.Drawing.Size(224, 25);
            this.txtTitle.TabIndex = 3;
            // 
            // dtpBirthday
            // 
            this.dtpBirthday.Location = new System.Drawing.Point(147, 149);
            this.dtpBirthday.Name = "dtpBirthday";
            this.dtpBirthday.Size = new System.Drawing.Size(173, 25);
            this.dtpBirthday.TabIndex = 9;
            // 
            // txtPrice
            // 
            this.txtPrice.Location = new System.Drawing.Point(147, 111);
            this.txtPrice.MaxLength = 8;
            this.txtPrice.Name = "txtPrice";
            this.txtPrice.Size = new System.Drawing.Size(103, 25);
            this.txtPrice.TabIndex = 5;
            this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(61, 216);
            this.btnOk.Name = "btnOk";
            this.btnOk.Size = new System.Drawing.Size(120, 34);
            this.btnOk.TabIndex = 10;
            this.btnOk.Text = "OK";
            this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(251, 216);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(120, 34);
            this.btnCancel.TabIndex = 11;
            this.btnCancel.Text = "返回";
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            // 
            // lblIsbn
            // 
            this.lblIsbn.Location = new System.Drawing.Point(58, 30);
            this.lblIsbn.Name = "lblIsbn";
            this.lblIsbn.Size = new System.Drawing.Size(83, 30);
            this.lblIsbn.TabIndex = 0;
            this.lblIsbn.Text = "ISBN";
            // 
            // lblTitle
            // 
            this.lblTitle.Location = new System.Drawing.Point(58, 72);
            this.lblTitle.Name = "lblTitle";
            this.lblTitle.Size = new System.Drawing.Size(83, 21);
            this.lblTitle.TabIndex = 2;
            this.lblTitle.Text = "标题";
            // 
            // lblSaleDate
            // 
            this.lblSaleDate.Location = new System.Drawing.Point(58, 156);
            this.lblSaleDate.Name = "lblSaleDate";
            this.lblSaleDate.Size = new System.Drawing.Size(83, 30);
            this.lblSaleDate.TabIndex = 8;
            this.lblSaleDate.Text = "发布日期";
            // 
            // lblPrice
            // 
            this.lblPrice.Location = new System.Drawing.Point(58, 114);
            this.lblPrice.Name = "lblPrice";
            this.lblPrice.Size = new System.Drawing.Size(83, 30);
            this.lblPrice.TabIndex = 4;
            this.lblPrice.Text = "价格";
            // 
            // frmBookDetail
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(8, 18);
            this.ClientSize = new System.Drawing.Size(608, 349);
            this.Controls.Add(this.lblPrice);
            this.Controls.Add(this.lblSaleDate);
            this.Controls.Add(this.lblTitle);
            this.Controls.Add(this.lblIsbn);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.btnOk);
            this.Controls.Add(this.txtPrice);
            this.Controls.Add(this.txtTitle);
            this.Controls.Add(this.txtIsbn);
            this.Controls.Add(this.dtpBirthday);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Name = "frmBookDetail";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "图书信息";
            this.Load += new System.EventHandler(this.frmBookDetail_Load);
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        public String CrudStatus
        {
            get { return _crudStatus; }
            set { _crudStatus = value; }
        }

        public string BookIsbn
        {
            get { return _userIsbn; }
            set { _userIsbn = value; }
        }

        private void frmBookDetail_Load(object sender, System.EventArgs e)
        {
            System.Diagnostics.Debug.Assert(_crudStatus != null, "状态未设置");

            SetUpInputLock();

            SetUpOkButtunTitle();

            LoadBookInfo();
        }

        private void LoadBookInfo()
        {
            try
            {
                if (_crudStatus.Equals("READ") || _crudStatus.Equals("DELETE") || _crudStatus.Equals("UPDATE"))
                {
                    Book book = (Book) mapper.QueryForObject("GetBookByIsbn", _userIsbn);
                    this.txtIsbn.Text = book.Isbn;
                    this.txtTitle.Text = book.Title;
                    this.txtPrice.Text = book.Price.ToString();
                    this.dtpBirthday.Value = book.SaleDate;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void SetUpInputLock()
        {
            if (_crudStatus.Equals("READ") || _crudStatus.Equals("DELETE"))
            {
                this.txtTitle.Enabled = false;
                this.txtPrice.Enabled = false;
                this.dtpBirthday.Enabled = false;
            }

            if (_crudStatus.Equals("READ") || _crudStatus.Equals("DELETE") || _crudStatus.Equals("UPDATE"))
            {
                this.txtIsbn.Enabled = false;
            }
        }

        private void SetUpOkButtunTitle()
        {
            if (_crudStatus.Equals("CREATE"))
            {
                this.btnOk.Text = "添加新数据";
            }
            else if (_crudStatus.Equals("UPDATE"))
            {
                this.btnOk.Text = "更新";
            }
            else if (_crudStatus.Equals("READ"))
            {
                this.btnOk.Text = "OK";
            }
            else if (_crudStatus.Equals("DELETE"))
            {
                this.btnOk.Text = "删除";
            }
        }

        private void btnOk_Click(object sender, System.EventArgs e)
        {
            try
            {
                Book book = new Book();
                if (_crudStatus.Equals("CREATE") || (_crudStatus.Equals("UPDATE")))
                {
                    book.Isbn = this.txtIsbn.Text;
                    book.Title = this.txtTitle.Text;
                    book.Price = int.Parse(this.txtPrice.Text);
                    book.SaleDate = new DateTime(this.dtpBirthday.Value.Year, this.dtpBirthday.Value.Month,
                        this.dtpBirthday.Value.Day);
                }

                if (_crudStatus.Equals("CREATE"))
                {
                    mapper.Insert("InsertBook", book);
                }
                if (_crudStatus.Equals("UPDATE"))
                {
                    mapper.Update("UpdateBook", book);
                }
                if (_crudStatus.Equals("DELETE"))
                {
                    mapper.Delete("DeleteBook", this.txtIsbn.Text);
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (DomainException ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().ToString(),
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().ToString(),
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                _logger.Error("在数据库更新时发生意外的错误!", ex);


                MessageBox.Show("发生意外的错误!" + "\r\r" + ex.Message,
                    ex.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }

frmBookView窗体后台代码:

 public class frmBookView : System.Windows.Forms.Form
    {
        private static readonly log4net.ILog _logger =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        //DomSqlMapBuilder,其作用是根据配置文件创建SqlMap实例。可以通过这个组件从Stream, Uri, FileInfo, or XmlDocument instance 来读取sqlMap.config文件。
        // SqlMap是线程安全的,也就是说,在一个应用中,可以共享一个SqlMap实例。
        private static string baseDir = Path.GetFullPath(@"../../");
        private static DomSqlMapBuilder builder = new DomSqlMapBuilder();
        private static ISqlMapper mapper = builder.Configure(baseDir + @"Resources\SqlMap.config");

        private DataSet _dataSet = null;
        private DataTable _dataTable = null;
        private System.Windows.Forms.DataGrid grdMain;
        private System.Windows.Forms.Button btnUpdate;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnCreate;
        private System.Windows.Forms.Button btnRead;
        private System.Windows.Forms.TextBox txtTitle;
        private System.Windows.Forms.Label lblTitle;
        private System.Windows.Forms.Button btnSearchTitle;
        private System.Windows.Forms.ComboBox cmbPrice;
        private System.Windows.Forms.ComboBox cmbPrice2;
        private System.Windows.Forms.Label lblPrice;
        private System.Windows.Forms.Button btnSearchPriceWeight;

        private System.ComponentModel.Container components = null;

        public frmBookView()
        {
            InitializeComponent();
        }

        /// 
        /// 运行后释放正在使用的资源
        /// 
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region 由Windows窗体设计器生成的代码

        private void InitializeComponent()
        {
            this.grdMain = new System.Windows.Forms.DataGrid();
            this.txtTitle = new System.Windows.Forms.TextBox();
            this.btnSearchTitle = new System.Windows.Forms.Button();
            this.btnRead = new System.Windows.Forms.Button();
            this.btnUpdate = new System.Windows.Forms.Button();
            this.btnCreate = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.lblTitle = new System.Windows.Forms.Label();
            this.cmbPrice = new System.Windows.Forms.ComboBox();
            this.cmbPrice2 = new System.Windows.Forms.ComboBox();
            this.lblPrice = new System.Windows.Forms.Label();
            this.btnSearchPriceWeight = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize) (this.grdMain)).BeginInit();
            this.SuspendLayout();
            // 
            // grdMain
            // 
            this.grdMain.AlternatingBackColor = System.Drawing.Color.White;
            this.grdMain.BackColor = System.Drawing.Color.White;
            this.grdMain.BackgroundColor = System.Drawing.Color.Gainsboro;
            this.grdMain.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.grdMain.CaptionBackColor = System.Drawing.Color.Silver;
            this.grdMain.CaptionFont = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Bold);
            this.grdMain.CaptionForeColor = System.Drawing.Color.Black;
            this.grdMain.CaptionVisible = false;
            this.grdMain.DataMember = "";
            this.grdMain.FlatMode = true;
            this.grdMain.Font = new System.Drawing.Font("Courier New", 9F);
            this.grdMain.ForeColor = System.Drawing.Color.DarkSlateGray;
            this.grdMain.GridLineColor = System.Drawing.Color.DarkGray;
            this.grdMain.HeaderBackColor = System.Drawing.Color.DarkGreen;
            this.grdMain.HeaderFont = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Bold);
            this.grdMain.HeaderForeColor = System.Drawing.Color.White;
            this.grdMain.LinkColor = System.Drawing.Color.DarkGreen;
            this.grdMain.Location = new System.Drawing.Point(26, 120);
            this.grdMain.Name = "grdMain";
            this.grdMain.ParentRowsBackColor = System.Drawing.Color.Gainsboro;
            this.grdMain.ParentRowsForeColor = System.Drawing.Color.Black;
            this.grdMain.ReadOnly = true;
            this.grdMain.SelectionBackColor = System.Drawing.Color.DarkSeaGreen;
            this.grdMain.SelectionForeColor = System.Drawing.Color.Black;
            this.grdMain.Size = new System.Drawing.Size(729, 348);
            this.grdMain.TabIndex = 10;
            this.grdMain.Paint += new System.Windows.Forms.PaintEventHandler(this.grdMain_Paint);
            // 
            // txtTitle
            // 
            this.txtTitle.Font = new System.Drawing.Font("MS UI Gothic", 11F, System.Drawing.FontStyle.Regular,
                System.Drawing.GraphicsUnit.Point, ((byte) (128)));
            this.txtTitle.Location = new System.Drawing.Point(115, 12);
            this.txtTitle.Name = "txtTitle";
            this.txtTitle.Size = new System.Drawing.Size(218, 26);
            this.txtTitle.TabIndex = 1;
            // 
            // btnSearchTitle
            // 
            this.btnSearchTitle.Location = new System.Drawing.Point(346, 12);
            this.btnSearchTitle.Name = "btnSearchTitle";
            this.btnSearchTitle.Size = new System.Drawing.Size(204, 36);
            this.btnSearchTitle.TabIndex = 2;
            this.btnSearchTitle.Text = "标题搜索(&T)";
            this.btnSearchTitle.Click += new System.EventHandler(this.btnSearchTitle_Click);
            // 
            // btnRead
            // 
            this.btnRead.Location = new System.Drawing.Point(26, 480);
            this.btnRead.Name = "btnRead";
            this.btnRead.Size = new System.Drawing.Size(179, 36);
            this.btnRead.TabIndex = 11;
            this.btnRead.Text = "查看(&R)";
            this.btnRead.Click += new System.EventHandler(this.btnRead_Click);
            // 
            // btnUpdate
            // 
            this.btnUpdate.Location = new System.Drawing.Point(384, 480);
            this.btnUpdate.Name = "btnUpdate";
            this.btnUpdate.Size = new System.Drawing.Size(179, 36);
            this.btnUpdate.TabIndex = 13;
            this.btnUpdate.Text = "更新(&U)";
            this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
            // 
            // btnCreate
            // 
            this.btnCreate.Location = new System.Drawing.Point(205, 480);
            this.btnCreate.Name = "btnCreate";
            this.btnCreate.Size = new System.Drawing.Size(179, 36);
            this.btnCreate.TabIndex = 12;
            this.btnCreate.Text = "追加(&C)";
            this.btnCreate.Click += new System.EventHandler(this.btnCreate_Click);
            // 
            // btnDelete
            // 
            this.btnDelete.Location = new System.Drawing.Point(563, 480);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(179, 36);
            this.btnDelete.TabIndex = 14;
            this.btnDelete.Text = "删除(&D)";
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // lblTitle
            // 
            this.lblTitle.Location = new System.Drawing.Point(51, 23);
            this.lblTitle.Name = "lblTitle";
            this.lblTitle.Size = new System.Drawing.Size(47, 25);
            this.lblTitle.TabIndex = 0;
            this.lblTitle.Text = "标题:";
            // 
            // cmbPrice
            // 
            this.cmbPrice.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbPrice.Font = new System.Drawing.Font("MS UI Gothic", 11.25F, System.Drawing.FontStyle.Regular,
                System.Drawing.GraphicsUnit.Point, ((byte) (128)));
            this.cmbPrice.Items.AddRange(new object[]
            {
                "1000",
                "2000",
                "3000",
                "4000",
                "5000"
            });
            this.cmbPrice.Location = new System.Drawing.Point(115, 75);
            this.cmbPrice.Name = "cmbPrice";
            this.cmbPrice.Size = new System.Drawing.Size(128, 27);
            this.cmbPrice.TabIndex = 4;
            // 
            // cmbPrice2
            // 
            this.cmbPrice2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbPrice2.Font = new System.Drawing.Font("MS UI Gothic", 11.25F, System.Drawing.FontStyle.Regular,
                System.Drawing.GraphicsUnit.Point, ((byte) (128)));
            this.cmbPrice2.Items.AddRange(new object[]
            {
                "",
                "以上",
                "以下"
            });
            this.cmbPrice2.Location = new System.Drawing.Point(243, 75);
            this.cmbPrice2.Name = "cmbPrice2";
            this.cmbPrice2.Size = new System.Drawing.Size(90, 27);
            this.cmbPrice2.TabIndex = 5;
            // 
            // lblPrice
            // 
            this.lblPrice.Location = new System.Drawing.Point(51, 82);
            this.lblPrice.Name = "lblPrice";
            this.lblPrice.Size = new System.Drawing.Size(47, 26);
            this.lblPrice.TabIndex = 3;
            this.lblPrice.Text = "价格:";
            // 
            // btnSearchPriceWeight
            // 
            this.btnSearchPriceWeight.Location = new System.Drawing.Point(346, 66);
            this.btnSearchPriceWeight.Name = "btnSearchPriceWeight";
            this.btnSearchPriceWeight.Size = new System.Drawing.Size(204, 36);
            this.btnSearchPriceWeight.TabIndex = 9;
            this.btnSearchPriceWeight.Text = "价格查询(&S)";
            this.btnSearchPriceWeight.Click += new System.EventHandler(this.btnSearchPriceWeight_Click);
            // 
            // frmBookView
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(8, 18);
            this.ClientSize = new System.Drawing.Size(790, 549);
            this.Controls.Add(this.btnSearchPriceWeight);
            this.Controls.Add(this.txtTitle);
            this.Controls.Add(this.cmbPrice);
            this.Controls.Add(this.cmbPrice2);
            this.Controls.Add(this.lblPrice);
            this.Controls.Add(this.lblTitle);
            this.Controls.Add(this.btnDelete);
            this.Controls.Add(this.btnCreate);
            this.Controls.Add(this.btnUpdate);
            this.Controls.Add(this.btnRead);
            this.Controls.Add(this.btnSearchTitle);
            this.Controls.Add(this.grdMain);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Name = "frmBookView";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "书籍一览";
            this.Load += new System.EventHandler(this.frmBookView_Load);
            ((System.ComponentModel.ISupportInitialize) (this.grdMain)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        #endregion

        /// 
        /// 当窗体加载的处理
        /// 
        private void frmBookView_Load(object sender, System.EventArgs e)
        {
            //设置列名
            _dataSet = new DataSet();
            _dataTable = _dataSet.Tables.Add("");
            DataColumn dc1 = _dataTable.Columns.Add("ISBN-KEY(隐藏)");
            DataColumn dc2 = _dataTable.Columns.Add("ISBN");
            DataColumn dc3 = _dataTable.Columns.Add("标题");
            DataColumn dc4 = _dataTable.Columns.Add("价格", typeof (int));
            DataColumn dc5 = _dataTable.Columns.Add("发布日期", typeof (DateTime));
            //创建数据样式
            DataGridTableStyle tableStyle = new DataGridTableStyle();
            tableStyle.MappingName = _dataTable.TableName;
            this.grdMain.TableStyles.Add(tableStyle);
            //风格
            DataGridTextBoxColumn tbc1 = new DataGridTextBoxColumn();
            DataGridTextBoxColumn tbc2 = new DataGridTextBoxColumn();
            DataGridTextBoxColumn tbc3 = new DataGridTextBoxColumn();
            DataGridTextBoxColumn tbc4 = new DataGridTextBoxColumn();
            DataGridTextBoxColumn tbc5 = new DataGridTextBoxColumn();
            tbc1.MappingName = dc1.ColumnName;
            tbc2.MappingName = dc2.ColumnName;
            tbc3.MappingName = dc3.ColumnName;
            tbc4.MappingName = dc4.ColumnName;
            tbc5.MappingName = dc5.ColumnName;
            //列的标题设置
            tbc1.HeaderText = dc1.ColumnName;
            tbc2.HeaderText = dc2.ColumnName;
            tbc3.HeaderText = dc3.ColumnName;
            tbc4.HeaderText = dc4.ColumnName;
            tbc5.HeaderText = dc5.ColumnName;
            // 设置右对齐和居中左对齐
            tbc1.Alignment = HorizontalAlignment.Left;
            tbc2.Alignment = HorizontalAlignment.Left;
            tbc3.Alignment = HorizontalAlignment.Left;
            tbc4.Alignment = HorizontalAlignment.Right;
            tbc5.Alignment = HorizontalAlignment.Left;
            // 设置列宽
            tbc1.Width = 0;
            tbc2.Width = 100;
            tbc3.Width = 140;
            tbc4.Width = 80;
            tbc5.Width = 80;
            //风格样式
            tableStyle.GridColumnStyles.Add(tbc1);
            tableStyle.GridColumnStyles.Add(tbc2);
            tableStyle.GridColumnStyles.Add(tbc3);
            tableStyle.GridColumnStyles.Add(tbc4);
            tableStyle.GridColumnStyles.Add(tbc5);
            //禁止设置行添加,删除,编辑数据
            _dataTable.DefaultView.AllowNew = false;
            _dataTable.DefaultView.AllowDelete = false;
            _dataTable.DefaultView.AllowEdit = false;
            this.grdMain.SetDataBinding(_dataTable.DefaultView, "");

            //价格的初始设定
            this.cmbPrice.SelectedIndex = 0;
            //名字搜索的执行
            showBooksByTitle();
        }


        /// 
        /// 名字搜索的执行
        /// 
        private void btnSearchTitle_Click(object sender, System.EventArgs e)
        {
            showBooksByTitle();
        }

        /// 
        /// 价格搜索的执行
        /// 
        private void btnSearchPriceWeight_Click(object sender, System.EventArgs e)
        {
            showBooksByPrice();
        }

        /// 
        /// 处理“浏览按钮”的时候
        /// 
        private void btnRead_Click(object sender, System.EventArgs e)
        {
            //如果这本书书号是有效的,“查看”对话框显示
            if (getBookIsbnBySelcectedRow() != "")
            {
                frmBookDetail frmdetail = new frmBookDetail();
                frmdetail.BookIsbn = getBookIsbnBySelcectedRow();
                frmdetail.CrudStatus = "READ";
                frmdetail.ShowDialog();
            }
        }

        /// 
        /// “添加”按钮被按下的时候处理
        /// 
        private void btnCreate_Click(object sender, System.EventArgs e)
        {
            //"添加"的书籍对话框显示
            frmBookDetail frmdetail = new frmBookDetail();
            frmdetail.CrudStatus = "CREATE";
            frmdetail.ShowDialog();
            //如果有变化,重新显示,
            if (frmdetail.DialogResult == DialogResult.OK)
            {
                showBooksByTitle();
            }
        }

        /// 
        /// 按“删除按钮”的时候处理
        /// 
        private void btnDelete_Click(object sender, System.EventArgs e)
        {
            //如果这本书书号是有效的“删除”对话框中显示
            if (getBookIsbnBySelcectedRow() != "")
            {
                frmBookDetail frmdetail = new frmBookDetail();
                frmdetail.BookIsbn = getBookIsbnBySelcectedRow();
                frmdetail.CrudStatus = "DELETE";
                frmdetail.ShowDialog();
                //刷新
                if (frmdetail.DialogResult == DialogResult.OK)
                {
                    showBooksByTitle();
                }
            }
        }

        /// 
        /// 更新
        /// 
        private void btnUpdate_Click(object sender, System.EventArgs e)
        {
            if (getBookIsbnBySelcectedRow() != "")
            {
                frmBookDetail frmdetail = new frmBookDetail();
                frmdetail.BookIsbn = getBookIsbnBySelcectedRow();
                frmdetail.CrudStatus = "UPDATE";
                frmdetail.ShowDialog();
                //刷新
                if (frmdetail.DialogResult == DialogResult.OK)
                {
                    showBooksByTitle();
                }
            }
        }

        /// 
        /// 名字搜索的执行
        /// 
        private void showBooksByTitle()
        {
            try
            {
                //LIKE搜索运行
                //IList books = Mapper.Instance().QueryForList("GetBookListByTitle", this.txtTitle.Text);
                IList books = mapper.QueryForList("GetBookListByTitle", this.txtTitle.Text);
                //清除数据
                _dataTable.Clear();
                //设置搜索结果的数据
                foreach (Book book in books)
                {
                    _dataTable.Rows.Add(new Object[]
                    {book.Isbn, book.IsbnWithHyphen, book.Title, book.Price, book.SaleDate});
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// 
        /// 价格搜索的执行
        /// 
        private void showBooksByPrice()
        {
            //价格搜索运行
            Hashtable param = new Hashtable();
            param.Add("price", this.cmbPrice.Text); //价格
            param.Add("priceCompare", this.cmbPrice2.Text); //「以上」or「以下」
            IList books = mapper.QueryForList("GetBookListByPrice", param);
            //清除数据
            _dataTable.Clear();
            //将搜索结果的数据
            foreach (Book book in books)
            {
                _dataTable.Rows.Add(new Object[] {book.Isbn, book.IsbnWithHyphen, book.Title, book.Price, book.SaleDate});
            }
        }

        /// 
        /// 获得所选择的行的书籍ISBN在数据
        /// 
        private string getBookIsbnBySelcectedRow()
        {
            string result = "";
            try
            {
                result = (string) grdMain[grdMain.CurrentCell.RowNumber, 0];
            }
            catch (Exception e)
            {
                //如果图书列表一个按钮被点击一个空白的状态(可能)
                _logger.Debug(e.Message);
            }
            return result;
        }

        private void grdMain_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            //点击的时候选择一整行
            if (_dataTable.Rows.Count != 0)
            {
                this.grdMain.Select(this.grdMain.CurrentCell.RowNumber);
            }
        }
    }

运行结果如图:

MyBatis.Net使用入门(三)_第2张图片

搜索结果:

MyBatis.Net使用入门(三)_第3张图片

查看详细:

MyBatis.Net使用入门(三)_第4张图片

更新数据:

MyBatis.Net使用入门(三)_第5张图片

删除数据:

MyBatis.Net使用入门(三)_第6张图片

其他相关文章

MyBatis.Net使用入门(二)
MyBatis.Net使用入门(一)

你可能感兴趣的:(MyBatis.Net框架)