DataGridView初試

來源:互聯網
上載者:User
 

1:拖一個DataGridView到form中去
2:首先設定表頭。表頭可以直接以DataGridView來設定,先設定column的數量,再來設定每個column的內容:
  this.dataGridView1.ColumnCount = 5;
            this.dataGridView1.Columns[0].Name = "表頭";
            this.dataGridView1.Columns[1].Name = "表頭";
            this.dataGridView1.Columns[2].Name = "表頭";
            this.dataGridView1.Columns[3].Name = "表頭";
            this.dataGridView1.Columns[4].Name = "表頭";
            this.dataGridView1.Columns[4].AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;

最後一行代表,這個列是自動擴充到整個寬度。
3:再來添加每一個row。在添加row之前需要對row中的每一個column進行設定,添加到row中,可以初始化一些內容。
在給row新增內容之前,還需要給這個row設定column的數量,然後才可以用row.Cells[index].value=""來設定儲存格的內容。
這裡有個簡單的方法設定row的column的數量
DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(this.dataGridView1);

就是這個row保持和dataGridview一樣的column。。

整體看代碼:

 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace post_table{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {                this.dataGridView1.ColumnCount = 5;            this.dataGridView1.Columns[0].Name = "表頭";            this.dataGridView1.Columns[1].Name = "表頭";            this.dataGridView1.Columns[2].Name = "表頭";            this.dataGridView1.Columns[3].Name = "表頭";            this.dataGridView1.Columns[4].Name = "表頭";            this.dataGridView1.Columns[4].AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;        }        private void button2_Click(object sender, EventArgs e)        {            int rowCount = 10;            int columnCount = 5;            for (int i = 0; i < rowCount; i++)            {                DataGridViewRow row = new DataGridViewRow();                row.CreateCells(this.dataGridView1);                for (int j = 0; j < columnCount; j++)                {                    row.Cells[j].Value = (i + 1) + "," + (j + 1);                }                dataGridView1.Rows.Add(row);            }        }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.