Skip to content

Instantly share code, notes, and snippets.

@ruyut
Created December 27, 2021 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruyut/3fff1cc55a32f8e9db660a5f170ddd86 to your computer and use it in GitHub Desktop.
Save ruyut/3fff1cc55a32f8e9db660a5f170ddd86 to your computer and use it in GitHub Desktop.
C# Dynamically generated DataGridView example
using System.Data;
using System.Windows.Forms;
namespace RuyutWinFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridView dataGridView = new DataGridView();
dataGridView.Dock = DockStyle.Fill; // 填滿視窗
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.Controls.Add(dataGridView); // 新增到當前的 Form 中
DataTable dataTable = new DataTable();
dataTable.Columns.Add("id", typeof(int));
dataTable.Columns.Add("name", typeof(string));
dataGridView.DataSource = dataTable;
for (int i = 0; i < 10; i++)
{
DataRow row = dataTable.NewRow();
row[0] = i;
row[1] = "name" + i;
dataTable.Rows.Add(row);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment