formdatatable.cs

来自「csharp课本的源代码」· CS 代码 · 共 43 行

CS
43
字号
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlTypes;

namespace CreateDataTableExample
{
    public partial class FormDataTable : Form
    {
        public FormDataTable()
        {
            InitializeComponent();
        }

        private void FormDataTable_Load(object sender, EventArgs e)
        {
            DataTable table = new DataTable("table1");
            //如果使用自动增量,类型必须定义为SqlInt64
            table.Columns.Add("id", typeof(SqlInt64));
            table.Columns["id"].AutoIncrement = true;
            DataColumn[] key = new DataColumn[1];
            key[0] = table.Columns["id"];
            table.PrimaryKey = key;
            //SqlString相当于SQL Server类型中的nvarchar
            table.Columns.Add("姓名", typeof(SqlString));
            table.Columns.Add("年龄", typeof(SqlInt32));
            table.Columns.Add("出生日期", typeof(SqlDateTime));
            DataRow row = table.NewRow();
            row["姓名"] = "张三";
            row["年龄"] = 20;
            //出生日期为1990年10月23日
            row["出生日期"] = new DateTime(1990, 10, 23);
            table.Rows.Add(row);
            dataGridView1.DataSource = table;

        }
       
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?