DataGridView dataGridView1 = new DataGridView(); this.Controls.Add(dataGridView1);
using System.Data; DataTable table = new DataTable(); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Age", typeof(int)); table.Rows.Add("John Smith", 25); table.Rows.Add("Jane Doe", 30); dataGridView1.DataSource = table;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;This code sets the AutoSizeColumnsMode property of the DataGridView control to AllCells, which causes the columns to automatically adjust their width depending on the content of the cells. These examples use the DataGridView control, which is part of the System.Windows.Forms namespace in the .NET Framework.