1. 程式人生 > >ADO.NET中DataTable的應用

ADO.NET中DataTable的應用

 

知識點

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 中,保留任何屬性設定以及初始值和當前值

 

 

 

 

 

示例程式碼和效果截圖

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;
using System.Configuration;
namespace VS
{
    public partial class Shoufeixiangmu : Form
    {
        private DataTable CourseTable;
        private DataView CourseViewByName;
        public Shoufeixiangmu()
        {
            InitializeComponent();
        }

        private void dataGridView1_BindingContextChanged(object sender, EventArgs e)
        {
            SqlConnection sqlConnection = new SqlConnection();                                              
            sqlConnection.ConnectionString =
            ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;                       

            SqlCommand sqlCommand2 = new SqlCommand();                                                      

            sqlCommand2.Connection = sqlConnection;                                                         

            sqlCommand2.CommandText = "SELECT * FROM Shoufeixiangmu;";                                          


            SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter();                                         
            sqlDataAdapter2.SelectCommand = sqlCommand2;                                                    
            DataTable studentTable = new DataTable();                                                       
            sqlConnection.Open();                                                                           
            //SQL資料介面卡讀取資料,並填充班級資料表;
            sqlDataAdapter2.Fill(studentTable);                                                             
            sqlConnection.Close();                                                                          
            this.dgv_Score.Columns.Clear();                                                                 
            this.dgv_Score.DataSource = studentTable;                                                       

            this.dgv_Score.Columns[this.dgv_Score.Columns.Count - 1].AutoSizeMode =                         
                DataGridViewAutoSizeColumnMode.Fill;


        }



        private void dgv_Score_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            if (this.dgv_Score.SelectionMode != DataGridViewSelectionMode.FullColumnSelect)
            {
                
                textBox1.Text = dgv_Score.Rows[e.RowIndex].Cells[0].Value.ToString();
                textBox2.Text = dgv_Score.Rows[e.RowIndex].Cells[1].Value.ToString();
                textBox3.Text = dgv_Score.Rows[e.RowIndex].Cells[2].Value.ToString();
                textBox4.Text = dgv_Score.Rows[e.RowIndex].Cells[3].Value.ToString();
                textBox5.Text = dgv_Score.Rows[e.RowIndex].Cells[4].Value.ToString();
                textBox6.Text = dgv_Score.Rows[e.RowIndex].Cells[5].Value.ToString();
                textBox7.Text = dgv_Score.Rows[e.RowIndex].Cells[6].Value.ToString();
                
            }
        }

        private void dgv_Score_SelectionChanged(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            SqlConnection sqlConnection = new SqlConnection();                                              
            sqlConnection.ConnectionString =
                "Server=(local);Database=EduBase2018;Integrated Security=sspi";                             
            SqlCommand sqlCommand = new SqlCommand();                                                       
            sqlCommand.Connection = sqlConnection;                                                          
            sqlCommand.CommandText = "SELECT * FROM Shoufeixiangmu;";
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                           
            sqlDataAdapter.SelectCommand = sqlCommand;                                                      
            sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;                            
            this.CourseTable = new DataTable();                                                             
            sqlConnection.Open();                                                                           
            sqlDataAdapter.Fill(this.CourseTable);                                                         
            
            sqlConnection.Close();                                                                          
                                                             
            this.CourseViewByName = new DataView();                                                         
            this.CourseViewByName.Table = this.CourseTable;                                                 
            this.CourseViewByName.Sort = "編號 ASC";  
            DataRow[] searchResultRows =
               this.CourseTable.Select("拼音碼 LIKE '%" + this.textBox8.Text.Trim() + "%'");             
            DataTable searchResultTable = this.CourseTable.Clone();                                         
            foreach (DataRow row in searchResultRows)                                                       
            {
                searchResultTable.ImportRow(row);                                                           
            }
            this.dgv_Score.DataSource = searchResultTable;    
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(comboBox1.Text=="按編號查詢"){
                SqlConnection sqlConnection = new SqlConnection();                                              
                sqlConnection.ConnectionString =
                    "Server=(local);Database=EduBase2018;Integrated Security=sspi";                             
                SqlCommand sqlCommand = new SqlCommand();                                                       
                sqlCommand.Connection = sqlConnection;                                                          
                sqlCommand.CommandText = "SELECT * FROM Shoufeixiangmu;";
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                           
                sqlDataAdapter.SelectCommand = sqlCommand;                                                      
                sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;                          
                this.CourseTable = new DataTable();                                                             
                sqlConnection.Open();                                                                           
                sqlDataAdapter.Fill(this.CourseTable);                                                          

                sqlConnection.Close();    
            DataRow searchResultRow = this.CourseTable.Rows.Find(this.textBox9.Text.Trim());       
            DataTable searchResultTable = this.CourseTable.Clone();                                       
            searchResultTable.ImportRow(searchResultRow);                                                
            this.dgv_Score.DataSource = searchResultTable;  }
            else if (comboBox1.Text == "按名稱查詢")
            {
                SqlConnection sqlConnection = new SqlConnection();                                              
                sqlConnection.ConnectionString =
                    "Server=(local);Database=EduBase2018;Integrated Security=sspi";                            
                SqlCommand sqlCommand = new SqlCommand();                                                       
                sqlCommand.Connection = sqlConnection;                                                          
                sqlCommand.CommandText = "SELECT * FROM Shoufeixiangmu;";
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                          
                sqlDataAdapter.SelectCommand = sqlCommand;                                                   
                sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;                            
                this.CourseTable = new DataTable();                                                           
                sqlConnection.Open();                                                                           
                sqlDataAdapter.Fill(this.CourseTable);                                                          

                sqlConnection.Close();
                                                               
                this.CourseViewByName = new DataView();                                                   
                this.CourseViewByName.Table = this.CourseTable;                                                 
                this.CourseViewByName.Sort = "名稱 ASC"; 
                DataRowView[] searchResultRowViews =
                this.CourseViewByName.FindRows(this.textBox9.Text.Trim());                       
                DataTable searchResultTable = this.CourseTable.Clone();                                       
                foreach (DataRowView dataRowView1 in searchResultRowViews)                                      
                {
                    searchResultTable.ImportRow(dataRowView1.Row);                                              
                }
                this.dgv_Score.DataSource = searchResultTable;
            }
        }
    }
}