zoukankan      html  css  js  c++  java
  • ADO.NET中DataTable的应用(读书笔记4)

    一.思维导图

     

    二.知识点描述

    DataTable是一个临时保存数据的网格虚拟表(表示内存中数据的一个表。)

    1.用法介绍:

    (1)可以使用相应的 DataTable 构造函数创建 DataTable 对象。 可以通过使用 Add 方法将其添加到 DataTable 对象的 Tables集合中,将其添加到 DataSet 中。

    (2)使用 DataAdapter 对象的 Fill 方法或 FillSchema 方法在 DataSet 中创建,或者使用 DataSet 的 ReadXml、ReadXmlSchema 或InferXmlSchema 方法从预定义的或推断的 XML 架构中创建。 请注意,将一个 DataTable 作为成员添加到一个 DataSet 的 Tables 集合中后,不能再将其添加到任何其他 DataSet 的表集合中。

    (3)在为 DataTable 定义了架构之后,可通过将 DataRow 对象添加到表的 Rows 集合中来将数据行添加到表中。

    2.在DataTable中处理数据

    (1)向数据表中添加数据

    (2)说明如何创建新行并将它们添加到表中。

    (3)查看数据表中的数据

    (4)说明如何访问行中的数据,包括数据的原始版本和当前版本。

    (5)Load 方法

    (6)说明如何通过 Load 方法使用行填充 DataTable。

    (7)DataTable 编辑

    (8)说明如何修改行中的数据,包括挂起对行的更改,直至验证并接受了建议的更改。

    (9)行状态与行版本

    (10)提供有关行的不同状态的信息。

    (11)DataRow 删除

    (12)说明如何从表中移除行。

    (13)行错误信息

    (14)说明如何插入每行的错误信息,帮助解决应用程序中的数据问题。

    (15)AcceptChanges 和 RejectChanges

    (16)说明如何接受或拒绝对行的更改。

    3.属性和方法

    (1)属性:

    名称 说明
    CaseSensitive 指示表中的字符串比较是否区分大小写
    Columns 获取属于该表的列的集合。
    DataSet 获取此表所属的 DataSet。
    HasErrors 获取一个值,该值指示该表所属的 DataSet 的任何表的任何行中是否有错误。
    Rows 获取属于该表的行的集合。
    TableName 获取或设置 DataTable 的名称

     

     

    (2)方法:

    名称 方法
    Clear 清除所有数据的 DataTable。
    Clone 克隆 DataTable 的结构,包括所有 DataTable 架构和约束。
    Compute 计算用来传递筛选条件的当前行上的给定表达式
    Copy 复制该 DataTable 的结构和数据。
    GetErrors 获取包含错误的 DataRow 对象的数组。
    GetType 获取当前实例的 Type。 (继承自 Object。)
    ImportRow 将 DataRow 复制到 DataTable 中,保留任何属性设置以及初始值和当前值

     

     

     

     

     

     

     

    三.示例代码和效果截图

    对DataTable执行初始化、数据填充、克隆等操作。

      1 using System;
      2 using System.Collections.Generic;
      3 using System.ComponentModel;
      4 using System.Data;
      5 using System.Drawing;
      6 using System.Linq;
      7 using System.Text;
      8 using System.Windows.Forms;
      9 using System.Data.SqlClient;
     10 using System.Configuration; 
     11 
     12 namespace LOGIN
     13 {
     14     public partial class OrdersTable : Form
     15     {
     16         private DataTable ordersTable;
     17         private DataView OrdersViewByName;
     18         private DataView OrdersViewBysupplyer;
     19         public OrdersTable()
     20         {
     21             InitializeComponent();
     22            
     23             //this.StartPosition = FormStartPosition.CenterScreen;                               
     24             this.dgv_orders.AllowUserToAddRows = false;                          
     25             //this.dgv_orders.RowHeadersVisible = false;                                                     
     26             this.dgv_orders.BackgroundColor = Color.White;                                  
     27             this.dgv_orders.AutoSizeColumnsMode =
     28                 DataGridViewAutoSizeColumnsMode.AllCells;                                      
     29         }
     30 
     31         private void OrdersTable_Load(object sender, EventArgs e)
     32         {
     33             SqlConnection sqlConnection = new SqlConnection();
     34             sqlConnection.ConnectionString =
     35                 "Server=(local);Database=MyHospital;Integrated Security=sspi";
     36             SqlCommand sqlCommand = new SqlCommand();
     37             SqlCommand sqlCommand1 = new SqlCommand();
     38          
     39             sqlCommand.Connection = sqlConnection;
     40             sqlCommand1.Connection = sqlConnection;
     41             
     42             sqlCommand.CommandText = "select OrderID,SupplyID,OrderKinds,OrderDate,GetDate,ProducePla,State,c.DrugName,cs.IndPrice,Num,TolPrice,cs.Guige FROM orders cs JOIN dbo.medicineData c ON cs.MedicineID=c.MedicineID;";
     43             sqlCommand1.CommandText = "select SupplyID,Supplyname from supplyer;";
     44             
     45             SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
     46             sqlDataAdapter.SelectCommand = sqlCommand;
     47             //DataTable ordersTable = new DataTable();
     48             SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter();                                        
     49             sqlDataAdapter1.SelectCommand = sqlCommand1;                                                 
     50             DataTable supplyerTable = new DataTable();
     51             sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;                           
     52             this.ordersTable = new DataTable();
     53             
     54             sqlConnection.Open();
     55             sqlDataAdapter.Fill(this.ordersTable);
     56             sqlDataAdapter1.Fill(supplyerTable);
     57            
     58             sqlConnection.Close();
     59             this.ordersTable.TableName = "tablename";
     60             this.OrdersViewByName = new DataView();                                                        
     61             this.OrdersViewByName.Table = this.ordersTable;                                                
     62             this.OrdersViewByName.Sort = "DrugName ASC";
     63 
     64             this.OrdersViewBysupplyer = new DataView();                                                        
     65             this.OrdersViewBysupplyer.Table = this.ordersTable;                                               
     66             this.OrdersViewBysupplyer.Sort = "ProducePla ASC";               
     67   
     68             this.dgv_orders.DataSource = ordersTable;
     69             dgv_orders.Columns["OrderID"].ReadOnly = true;
     70             dgv_orders.Columns["OrderKinds"].ReadOnly = true;
     71             dgv_orders.Columns["State"].ReadOnly = true;
     72             dgv_orders.Columns["DrugName"].ReadOnly = true;
     73             dgv_orders.Columns["OrderID"].HeaderText = "订单号";
     74             dgv_orders.Columns["SupplyID"].Visible=false;
     75             dgv_orders.Columns["OrderKinds"].HeaderText = "订单";
     76             dgv_orders.Columns["OrderDate"].HeaderText = "订单日期";
     77             dgv_orders.Columns["GetDate"].HeaderText = "到货日期";
     78             dgv_orders.Columns["ProducePla"].HeaderText = "生产地";
     79             dgv_orders.Columns["State"].HeaderText = "是否入库";
     80             dgv_orders.Columns["DrugName"].HeaderText = "药品";
     81             dgv_orders.Columns["DrugName"].DisplayIndex=3;
     82             dgv_orders.Columns["IndPrice"].HeaderText = "单价";
     83             dgv_orders.Columns["Num"].HeaderText = "数量";
     84             dgv_orders.Columns["TolPrice"].HeaderText = "总价";
     85             dgv_orders.Columns["Guige"].HeaderText = "规格";
     86             this.dgv_orders.Columns[this.dgv_orders.Columns.Count - 1].AutoSizeMode =                       
     87                 DataGridViewAutoSizeColumnMode.Fill;
     88 
     89             DataGridViewComboBoxColumn supplyerColumn = new DataGridViewComboBoxColumn();                   
     90             supplyerColumn.Name = "Supplyname";                                                                  
     91             supplyerColumn.HeaderText = "供应商";                                                           
     92             supplyerColumn.DataSource = supplyerTable;
     93             supplyerColumn.DisplayMember = "Supplyname";                                                             
     94             supplyerColumn.ValueMember = "SupplyID";                                                             
     95             supplyerColumn.DataPropertyName = "SupplyID";                                                 
     96             supplyerColumn.DisplayIndex = 1;                                                               
     97             //supplyerColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;                           
     98             this.dgv_orders.Columns.Add(supplyerColumn);
     99 
    100             DataGridViewColumn medicineColumn = new DataGridViewColumn();                      
    101             medicineColumn.Name = "medicine";                                                                   
    102             medicineColumn.HeaderText = "药品名";
    103             
    104 
    105             
    106             
    107         }
    108 
    109         private void update_Click(object sender, EventArgs e)
    110         {
    111             SqlConnection sqlConnection = new SqlConnection();                                           
    112             sqlConnection.ConnectionString =
    113                 ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;                             
    114             SqlCommand updateCommand = new SqlCommand();                                                  
    115             updateCommand.Connection = sqlConnection;                                                         
    116             updateCommand.CommandText =                                                                      
    117                 "UPDATE orders"
    118                 + " SET SupplyID=@SupplyID,OrderDate=@OrderDate,GetDate=@GetDate,ProducePla=@ProducePla,IndPrice=@IndPrice,Num=@Num,TolPrice=@TolPrice,Guige=@Guige,state=@state"
    119                 + " WHERE OrderID=@OrderID;";
    120             updateCommand.Parameters.Add("@OrderID", SqlDbType.Char, 10, "OrderID");
    121             updateCommand.Parameters.Add("@SupplyID", SqlDbType.Char, 10, "SupplyID");                      
    122             updateCommand.Parameters.Add("@OrderDate", SqlDbType.DateTime, 0, "OrderDate");
    123             updateCommand.Parameters.Add("@GetDate", SqlDbType.DateTime, 0, "GetDate");
    124             updateCommand.Parameters.Add("@ProducePla", SqlDbType.VarChar, 0, "ProducePla");
    125             updateCommand.Parameters.Add("@IndPrice", SqlDbType.Char, 0, "IndPrice");
    126             updateCommand.Parameters.Add("@Num", SqlDbType.Int, 0, "Num");
    127             updateCommand.Parameters.Add("@TolPrice", SqlDbType.Int, 10, "TolPrice");
    128             updateCommand.Parameters.Add("@Guige", SqlDbType.VarChar, 10, "Guige");                        
    129             updateCommand.Parameters.Add("@state", SqlDbType.Int, 0, "state");
    130 
    131 
    132             SqlCommand deleteCommand = new SqlCommand();                                                
    133             deleteCommand.Connection = sqlConnection;                                                      
    134             deleteCommand.CommandText =                                                                  
    135                 "DELETE orders"
    136                 + " WHERE OrderID=@OrderID;";
    137             deleteCommand.Parameters.Add("@OrderID", SqlDbType.Char, 10, "OrderID");
    138             SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                         
    139             //sqlDataAdapter.InsertCommand = insertCommand;                                                   
    140             sqlDataAdapter.UpdateCommand = updateCommand;                                               
    141             sqlDataAdapter.DeleteCommand = deleteCommand;                                                   
    142             DataTable studentTable1 = (DataTable)this.dgv_orders.DataSource;                                
    143             sqlConnection.Open();                                                                           
    144             int rowAffected = sqlDataAdapter.Update(studentTable1);                                         
    145             sqlConnection.Close();                                                                          
    146             MessageBox.Show("更新" + rowAffected.ToString() + "行。");     
    147         }
    148 
    149         private void input_Click(object sender, EventArgs e)
    150         {
    151             Orders f = new Orders();
    152             f.Show();
    153         }
    154 
    155         private void search_Click(object sender, EventArgs e)
    156         {
    157             
    158             if (this.comboBox1.SelectedIndex == 0 && this.search.Text != "") 
    159             {
    160                 DataRow searchResultRow = this.ordersTable.Rows.Find(this.textBox1.Text.Trim());            
    161                 DataTable searchResultTable = this.ordersTable.Clone();                                      
    162                 searchResultTable.ImportRow(searchResultRow);                                              
    163                 this.dgv_orders.DataSource = searchResultTable;
    164             }
    165             else if (this.comboBox1.SelectedIndex == 1 && this.search.Text != "")
    166             {
    167                 DataRowView[] searchResultRowViews = 
    168                 this.OrdersViewByName.FindRows(this.textBox1.Text.Trim());                      
    169             DataTable searchResultTable = this.ordersTable.Clone();                                     
    170             foreach (DataRowView dataRowView1 in searchResultRowViews)                                 
    171             {
    172                 searchResultTable.ImportRow(dataRowView1.Row);                                          
    173             }
    174             this.dgv_orders.DataSource = searchResultTable; 
    175             }
    176             else if (this.comboBox1.SelectedIndex == 2 && this.search.Text != "")
    177             {
    178                 DataRowView[] searchResultRowViews =
    179                 this.OrdersViewBysupplyer.FindRows(this.textBox1.Text.Trim());            
    180                 DataTable searchResultTable = this.ordersTable.Clone();                                       
    181                 foreach (DataRowView dataRowView1 in searchResultRowViews)                                     
    182                 {
    183                     searchResultTable.ImportRow(dataRowView1.Row);                                     
    184                 }
    185                 this.dgv_orders.DataSource = searchResultTable; 
    186             }
    187             
    188            
    189         }
    190     }
    191 }

  • 相关阅读:
    Codeforces.468C.Hack it!(构造)
    BZOJ.3227.[SDOI2008]红黑树tree(树形DP 思路)
    146
    145
    144
    143
    142
    141
    140
    139
  • 原文地址:https://www.cnblogs.com/lidie-/p/9860029.html
Copyright © 2011-2022 走看看