DataGridView初試

NO IMAGE

 

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);
}
}
}
}