2016年9月13日 星期二

[C#] DataTable 使用select搜尋並修改欄位

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//載入DataTable
using System.Data;

namespace DataTable_Select
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a table of five different people.
            // ... Store their size and sex.
            DataTable table = new DataTable("School");
            table.Columns.Add(new DataColumn("Number", typeof(int)));
            table.Columns.Add(new DataColumn("Name", typeof(string)));

            table.Rows.Add(1, "Kevin");
            table.Rows.Add(2, "Justin");
            table.Rows.Add(3, "Chris");
            table.Rows.Add(4, "Fiona");
            table.Rows.Add(5, "John");

            // Search for people above a certain size.
            // ... Require certain sex.
            DataRow[] result = table.Select("Name = 'Fiona'");

            //修改前
            //DataTable table = GetTable(); // 取得資料表
            foreach (DataRow row in table.Rows) // 讀取行
            {
                Console.WriteLine("--- Row ---"); // Print separator.
                foreach (var item in row.ItemArray) // 讀取每個項目
                {
                    Console.Write("Item: "); // Print label.
                    Console.WriteLine(item); // Invokes ToString abstract method.
                }
            }

            //修改中
            for (int i = 0; i < result.Length; i++)
            {
                Console.WriteLine(result[i][0] + "\t" + result[i][1]);
                Console.WriteLine("取得搜尋的行號:"+i);
                result[i][1] = "May";
            }

            //修改後
            //DataTable table = GetTable(); // 取得資料表
            foreach (DataRow row in table.Rows) // 讀取行
            {
                Console.WriteLine("--- Row ---"); // Print separator.
                foreach (var item in row.ItemArray) // 讀取每個項目
                {
                    Console.Write("Item: "); // Print label.
                    Console.WriteLine(item); // Invokes ToString abstract method.
                }
            }

            Console.ReadLine();
        }
    }
}



程式檔案:

沒有留言:

張貼留言