C# DataGridView Add Columns and Rows

The DataGridView control is carefully crafted to serve as a comprehensive solution for effortlessly presenting tabular data within Windows Forms. It surpasses expectations with its remarkable versatility, as it boasts an extensive array of properties, methods, and events, all carefully designed to empower developers with the ability to tailor its visual presentation and operational characteristics according to specific requirements. As a testament to its adaptability, every cell within the DataGridView control inherits from the fundamental DataGridViewCell base class, ensuring consistent behavior and a unified structure throughout.

Columns collection, Rows collection

To further enhance flexibility and accessibility, the DataGridView control provides convenient access to its columns and rows. Developers can effortlessly navigate and manipulate the columns by using the Columns collection, enabling seamless customization and management of column-related properties and operations. Similarly, the Rows collection serves as a gateway to efficiently interact with and control the rows within the DataGridView control, facilitating dynamic updates, data retrieval, and manipulation with ease and precision.

The following C# source code shows how to manually create Columns and Rows in a DataGridView.

dataGridView1.Columns[Index].Name = "Column Name";
Full Source C#
using System; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { dataGridView1.ColumnCount = 3; dataGridView1.Columns[0].Name = "Product ID"; dataGridView1.Columns[1].Name = "Product Name"; dataGridView1.Columns[2].Name = "Product Price"; string[] row = new string[] { "1", "Product 1", "1000" }; dataGridView1.Rows.Add(row); row = new string[] { "2", "Product 2", "2000" }; dataGridView1.Rows.Add(row); row = new string[] { "3", "Product 3", "3000" }; dataGridView1.Rows.Add(row); row = new string[] { "4", "Product 4", "4000" }; dataGridView1.Rows.Add(row); } } }