- 1 year ago
Showing more than one row in DataGridView in C#
To display multiple rows in a DataGridView control in C#, you need to populate the DataGridView with data from a data source, such as a DataTable or a list of objects. Here's an example of how you can accomplish this:
Create a DataTable or a list of objects that represent the data you want to display in the DataGridView.
csharpDataTable dataTable = new DataTable();
// Add columns to the DataTable
dataTable.Columns.Add("Column1");
dataTable.Columns.Add("Column2");
// Add rows to the DataTable
dataTable.Rows.Add("Row 1 Data 1", "Row 1 Data 2");
dataTable.Rows.Add("Row 2 Data 1", "Row 2 Data 2");
Bind the DataTable or list of objects to the DataGridView's DataSource property.
csharpdataGridView.DataSource = dataTable;
Alternatively, if you are using a list of objects, you can set the DataSource to the list directly.
csharpList<MyDataObject> dataList = new List<MyDataObject>();
// Add data objects to the list
dataGridView.DataSource = dataList;
Customize the appearance and behavior of the DataGridView as needed, such as column headers, column widths, cell formatting, etc.
csharp// Set column headers
dataGridView.Columns["Column1"].HeaderText = "Column 1";
dataGridView.Columns["Column2"].HeaderText = "Column 2";
// Set column widths
dataGridView.Columns["Column1"].Width = 150;
dataGridView.Columns["Column2"].Width = 200;
// Apply cell formatting or styling
// ...
With these steps, you should be able to display multiple rows in the DataGridView control in C#. The DataGridView will automatically generate the necessary rows and columns based on the data source you provide.