create grid in csharp

To create a grid in C# using Windows Forms, you can use the DataGridView control. Here's an example of creating a DataGridView control and configuring it to display a grid:

main.cs
using System.Windows.Forms;

// create new DataGridView control
var dataGridView = new DataGridView();

// configure grid properties
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.ReadOnly = true;

// add grid to parent control
this.Controls.Add(dataGridView);
558 chars
17 lines

This code creates a new DataGridView control and configures it to display a grid with no option to add or delete rows, rows that can't be resized, and columns that automatically adjust to fill the control. The grid is also set to automatically resize based on the content of the columns, and is docked to fill the parent control. Finally, the grid is set to read-only mode so that the user can't edit the content.

You can then populate the DataGridView control with data by setting its DataSource property to a data source, such as a DataTable or a list of objects.

related categories

gistlibby LogSnag