DataTable 赋值取值

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataTableLearn
{
    public partial class Form1 : Form
    {
        DataTable dt = new DataTable("Table");//创建表
        DataTable newdt = new DataTable("NewTable");
        public Form1()
        {
            InitializeComponent();
            dt.CaseSensitive = false;//不区分大小写
            #region 添加列

            dt.Columns.Add("column1", System.Type.GetType("System.String"));

            DataColumn dc1 = new DataColumn("column2", System.Type.GetType("System.Boolean"));
            dt.Columns.Add(dc1);

            DataColumn dc2 = new DataColumn();
            dc2.DataType = typeof(System.Int32);
            dc2.ColumnName = "column3";
            dt.Columns.Add(dc2);
            #endregion

            #region 赋值
            for (int i = 0; i <= 3; i++)
            {
                DataRow dr = dt.NewRow();//创建新的行
                dr[0] = "NewRow" + i;
                dr[1] = true;
                dr[2] = i;
                dt.Rows.Add(dr);
            }

            DataRow dr1 = dt.NewRow();
            dr1["column1"] = "AX";
            dr1["column2"] = true;
            dr1["column3"] = 100;
            dt.Rows.Add(dr1);//对特定表添加特定列
            #endregion

            dataGridView1.DataSource = dt;
        }
        //重新赋值
        private void button4_Click(object sender, EventArgs e)
        {
            //对dt的操作
            //Method 1
            DataRow drOperate = dt.Rows[0];
            drOperate["column1"] = "AXzhz";
            drOperate["column2"] = false;
            //Method 2
            drOperate[0] = "AXzhz";
            drOperate[1] = false;
            //Method 3
            dt.Rows[0]["column1"] = "AXzhz";
            dt.Rows[0]["column2"] = false;
            //Method 4
            dt.Rows[0][0] = "AXzhz";
            dt.Rows[0][1] = false;
        }
        //取值
        private void button5_Click(object sender, EventArgs e)
        {
            label1.Text = dt.Rows[0][0].ToString();
            label1.Text = dt.Rows[0]["column1"].ToString();
        }

你可能感兴趣的:(#,ADO.NET,DataTable,赋值取值)