ADO.Net中DataTable的应用

一、知识点描述

1、DataTable概念

在 ADO.NET 中,DataTable对象用于表示 DataSet 中的表。DataTable 表示一个内存内关系数据的表;它提供了对表中行列数据对象的各种操作。可以直接将数据从数据库填充到DataTable对象中,也可以将DataTable对象添加到现有的DataSet对象中。

 

2、关于datatable的创建

(1)创建DataTable对象

可以通过以下两种方式创建DataTable对象:

1) 通过DataTable类的构造函数创建DataTable对象,例如:

DataTable table = new DataTable(); 

2) 通过DataSet的Tables对象的Add方法创建DataTable对象,例如:

DataSet dataset = new DataSet();  

DataTable table = dataset.Tables.Add("medicine"); 

2)在DataTable对象中添加列

在DataTable对象中添加列的最常用的方法是通过DataTable对象的Column属性中的Add方法。添加后的每一列都是一个DataColumn对象。

3)在DataTable对象中创建行

DataTable对象的每一行都是一个DataRow对象,所以创建行时可以先利用DataTable对象的NewRow方法创建一个DataRow对象,并设置新行中各列的数据,然后利用Add方法将DataRow对象添加到表中

4)将SQL Server数据库中的表填充到DataTable

除了可以直接创建ADO.NET对象DataTable的行列信息外,也可以通过DateAdapter对象的Fill方法将SQL Server数据库中的表填充到DataTable对象中。

 

 

3、DataTable的常用对象

包括connection对象,command对象,datareader对象,DataAdapter对象。

(1)connection对象:获取或设置SqlCommand的实例使用的SqlConnection。

(2)command对象:获取或设置要对数据源执行的Transact—SQL语句或存储过程。,

(3)datareader对象:此方法用于用户进行的查询操作。使用SqlDataReader对象的Read();方法进行逐行读取,

(4)DataAdapter对象:SQL数据适配器读取数据,并填充表;。

 

4、下面将介绍关于DataTable的具体实例:SQLConnection对象,SQLCommand对象,SQLDataAdaper对象,DataTable(DataColum和DataRow)

(1)SQLConnection对象

SqlConnection sqlConnection = new SqlConnection();

sqlConnection.ConnectionString =

                "Server=(local);Database=Edubase2018;Integrated Security=sspi";

(2)SQLCommand对象

SqlCommand insertCommand = sqlConnection.CreateCommand();                                                      //SQL命令的连接属性指向SQL连接;

            insertCommand.CommandText =

                "INSERT tb_ExitMedicine(Piaono,P_name,admissionno,R_name,M_name,pinyin,number,price,time,reason)"+

              " values('" + cmb_piaono.Text.Trim() + "','" + txt_doc.Text.Trim() + "','" + txt_admissionno.Text.Trim() + "','" + txt_room.Text.Trim() + "','" + txt_name.Text.Trim() + "'"+ ",'" + txt_chinese.Text.Trim() + "','" + txt_exitnum.Text.Trim() + "','" + Convert.ToDecimal(txt_price.Text.Trim()) + "','" + dtp_date.Value.ToShortDateString() + "','" + txt_note.Text + "')";

(3)SQLDataAdaper对象

SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                           //声明并实例化SQL数据适配器;

sqlDataAdapter.SelectCommand = sqlCommand;

(4)DataTable(DataColumDataRow)

DataRow  DataColumn 对象是 DataTable 的主要组件。使用 DataRow 对象及其属性和方法检索、评估、插入、删除和更新 DataTable 中的值。DataRowCollection 表示 DataTable 中的实际 DataRow 对象,DataColumnCollection 中包含用于描述DataTable 的架构的 DataColumn 对象。使用重载的 Item 属性返回或设置 DataColumn 的值。

二、思维导图

三、示例代码

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

namespace 护士工作站2

{

    public partial class 退药 : Form

    {

       

        public 退药()

        {

            InitializeComponent();

           

            this.StartPosition = FormStartPosition.CenterScreen;                                            //本窗体启动位置设为屏幕中央;

            this.dgv_UseMedicine.AllowUserToAddRows = false;                                                      //数据网格视图不允许用户添加行;

            this.dgv_UseMedicine.RowHeadersVisible = false;                                                       //数据网格视图的行标题不可见;

            this.dgv_UseMedicine.BackgroundColor = Color.White;                                                   //数据网格视图的背景色设为白色;

            this.dgv_UseMedicine.AutoSizeColumnsMode =

                DataGridViewAutoSizeColumnsMode.AllCells;

           

        }

      

        private void button1_Click(object sender, EventArgs e)

        {   if (cmb_piaono.Text == "")

                return;

            SqlConnection sqlConnection = new SqlConnection();                                              //声明并实例化SQL连接;

            sqlConnection.ConnectionString =

                "Server=(local);Database=Edubase2018;Integrated Security=sspi";                             //在字符串变量中,描述连接字符串所需的服务器地址、数据库名称、集成安全性(即是否使用Windows验证);

            SqlCommand insertCommand = sqlConnection.CreateCommand();                                                      //SQL命令的连接属性指向SQL连接;

            insertCommand.CommandText =

                "INSERT tb_ExitMedicine(Piaono,P_name,admissionno,R_name,M_name,pinyin,number,price,time,reason)"+

              " values('" + cmb_piaono.Text.Trim() + "','" + txt_doc.Text.Trim() + "','" + txt_admissionno.Text.Trim() + "','" + txt_room.Text.Trim() + "','" + txt_name.Text.Trim() + "'"+ ",'" + txt_chinese.Text.Trim() + "','" + txt_exitnum.Text.Trim() + "','" + Convert.ToDecimal(txt_price.Text.Trim()) + "','" + dtp_date.Value.ToShortDateString() + "','" + txt_note.Text + "')";

            int sum = Convert.ToInt32(txt_num.Text) - Convert.ToInt32(txt_exitnum.Text);

            if (sum < 0)

            {

                MessageBox.Show("你输入的数量过大!!");

                return;

            }

            else

            {

                decimal price = Convert.ToDecimal(txt_price.Text) * sum;

 

              

              

            

            }                                         //指定SQL命令的命令文本;该命令插入选课记录;

            insertCommand.Parameters.AddWithValue("@Piaono", this.cmb_piaono.Text.Trim());

            insertCommand.Parameters.AddWithValue("@P_name", this.txt_doc.Text.Trim());

            insertCommand.Parameters.AddWithValue("@admissionno", this.txt_admissionno.Text.Trim());

            insertCommand.Parameters.AddWithValue("@R_name", this.txt_room.Text.Trim());

            insertCommand.Parameters.AddWithValue("@M_name", this.txt_name.Text.Trim());

            insertCommand.Parameters.AddWithValue("@pinyin", this.txt_chinese.Text.Trim());

            insertCommand.Parameters.AddWithValue("@number", this.txt_exitnum.Text.Trim());

            insertCommand.Parameters.AddWithValue("@price", this.txt_price.Text.Trim());

           

            insertCommand.Parameters.AddWithValue("@time", this.dtp_date.Text.Trim());

            insertCommand.Parameters.AddWithValue("@reason", this.txt_note.Text.Trim());

         

 

            //SQL命令的参数集合添加参数的名称、SQL Server数据类型、长度(仅用于定长类型)、所绑定的数据表中的列名;

           

                                                           //SQL数据适配器的更新命令属性指向SQL命令;

            sqlConnection.Open();

             //打开SQL连接;

            int rowAffected = insertCommand.ExecuteNonQuery ();                              //SQL数据适配器根据学生数据表提交更新,并返回受影响行数;

            sqlConnection.Close();                                                                          //关闭SQL连接;

            MessageBox.Show("退药成功");

         

          

        }

 

     

        private void 载入_Click(object sender, EventArgs e)

        {

           SqlConnection sqlConnection = new SqlConnection();                                              //声明并实例化SQL连接;

            sqlConnection.ConnectionString =

                "Server=(local);Database=Edubase2018;Integrated Security=sspi";                             //在字符串变量中,描述连接字符串所需的服务器地址、数据库名称、集成安全性(即是否使用Windows验证);

            SqlCommand sqlCommand = new SqlCommand();                                                       //声明并实例化SQL命令;

                                                                 //声明并实例化SQL命令;

            sqlCommand.Connection = sqlConnection;                                                          //SQL命令的连接属性指向SQL连接;

                                                                     //SQL命令的连接属性指向SQL连接;

            sqlCommand.CommandText = "SELECT * FROM tb_UseMedicine where admissionno=@admissionno ";

            sqlCommand.Parameters.AddWithValue("@admissionno", this.txb_no.Text.Trim());//指定SQL命令的命令文本;该命令查询所有班级,以用作下拉框数据源;

                                                    //指定SQL命令的命令文本;该命令查询所有学生;

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                           //声明并实例化SQL数据适配器;

            sqlDataAdapter.SelectCommand = sqlCommand;                                                      //SQL数据适配器的查询命令属性指向SQL命令;

                                                    //声明并实例化SQL数据适配器;

                                                             //SQL数据适配器的查询命令属性指向SQL命令;

            DataTable UseMedicineTable = new DataTable();                                                       //声明并实例化数据表,用于保存所有学生,以用作数据网格视图的数据源;

            sqlConnection.Open();                                                                           //打开SQL连接;

            sqlDataAdapter.Fill(UseMedicineTable);                                                                //SQL数据适配器读取数据,并填充班级数据表;

                                                                       //SQL数据适配器读取数据,并填充学生数据表;

            sqlConnection.Close();                                                                          //关闭SQL连接;

            this.dgv_UseMedicine.Columns.Clear();                                                                 //数据网格视图的列集合清空;

            this.dgv_UseMedicine.DataSource = UseMedicineTable;

            this.dgv_UseMedicine.Columns["piaono"].HeaderText = "票号";//将数据网格视图的数据源设为学生数据表;

            this.dgv_UseMedicine.Columns["D_name"].HeaderText = "医师";                                               //将数据网格视图的指定列的表头文本设为中文;

            this.dgv_UseMedicine.Columns["admissionno"].HeaderText = "病历号";

            this.dgv_UseMedicine.Columns["P_name"].HeaderText = "病人";

            this.dgv_UseMedicine.Columns["R_name"].HeaderText = "科室";

           

            this.dgv_UseMedicine.Columns["M_name"].HeaderText = "药名";

            this.dgv_UseMedicine.Columns["pinyin"].HeaderText = "拼音";

            this.dgv_UseMedicine.Columns["number"].HeaderText = "数量";

            this.dgv_UseMedicine.Columns["price"].HeaderText = "价格";

            this.dgv_UseMedicine.Columns["shifou"].HeaderText = "是否退药";

                                                       //将数据网格视图的指定列设为不可见;

           

        }

 

        private void 退药_Load(object sender, EventArgs e)

        {

          

        }

 

        private void dgv_UseMedicine_CellContentClick(object sender, DataGridViewCellEventArgs e)

        {

           

           

        }

 

        private void cmb_piaono_SelectedIndexChanged(object sender, EventArgs e)

        {

           

        

        }

 

        private void dgv_UseMedicine_MouseClick(object sender, MouseEventArgs e)

        {

           

            txt_admissionno.Text = dgv_UseMedicine.CurrentRow.Cells[3].Value.ToString();

            txt_doc.Text = dgv_UseMedicine.CurrentRow.Cells[1].Value.ToString();

            cmb_piaono.Text = dgv_UseMedicine.CurrentRow.Cells[0].Value.ToString();

            txt_name.Text = dgv_UseMedicine.CurrentRow.Cells[5].Value.ToString();

            txt_num.Text = dgv_UseMedicine.CurrentRow.Cells[7].Value.ToString();

            txt_price.Text = dgv_UseMedicine.CurrentRow.Cells[8].Value.ToString();

            txt_chinese.Text = dgv_UseMedicine.CurrentRow.Cells[6].Value.ToString();

          

            txt_room.Text = dgv_UseMedicine.CurrentRow.Cells[4].Value.ToString();

           

 

   }

 

        private void txt_id_TextChanged(object sender, EventArgs e)

        {

 

        }

       

          

    }

        }

   

四、效果截图

posted @ 2018-11-04 14:19  东京塔  阅读(197)  评论(0编辑  收藏  举报