強型別DataSet的使用簡明教程

來源:互聯網
上載者:User

關於弱類型 DataSet的缺點:

  • 無論何時從 DataSet檢索值都是以Object類型返回,需要對它進行類型轉換;
  • 給其它開發人員使用 時無法知道哪些列可用;
  • 運行時才能知道所 有列名,資料繫結麻煩。

因此,VS為我們提供強型別DataSet的自動產生功能。


 

 

下面簡單的來使用一下。

 

首先,建一個控制台工程,然後再項目名那右鍵添加新項,選擇一個基於服務的資料庫,取名 test 。

 

 

在資料庫中新 建一個表,表名為T_Person,表 結構如下:


 

 

然後為資料庫中建立一個表並添加一些資料。

 

 

 

 

再在項目中添加一個資料集新項,然後直接從左邊伺服器總管中將表 T_Person 拖入設 計視圖中,我們的強 類型的 DataSet 就建好了!

 

 

最後來看看怎麼在程式中使用它:

代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Test.DataSet1TableAdapters;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            T_PersonTableAdapter personTableAdapter = new T_PersonTableAdapter();

            //通過GetData()方法返回一個Table
            DataSet1.T_PersonDataTable table = personTableAdapter.GetData();

            foreach (DataSet1.T_PersonRow row in table)
            {
                //注意到這裡我們就是像屬性一樣的取得資料了
                Console.WriteLine(row.name);
            }

            Console.ReadKey();
        }
    }
}

 

運行結果 如下:

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.