Populate Data Into DataGridView using For-Loop in C#/CSharp

The following example will populate data into a DataGridView Control using For-Loop.

To begin with:
1.) Create a new C# Project.
2.) Add a DataGridView Control onto Form1.
3.) Then copy the code below and paste on Form1_Load() event.


  Random rand = new Random();
 DataGridView dgv = this.dataGridView1;

 //DATAGRIDVIEW SETTING
 dgv.AllowUserToAddRows = false;
 dgv.RowHeadersVisible = false;
 dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

 //ADD COLUMN HEADERS
 dgv.Columns.Add("Product", "Product");
 dgv.Columns.Add("Price", "Price");

 //ADD 10 ROWS
 dgv.Rows.Add(10);

 //NOW, POPULATE THE DATA INTO THE CELLS
 for (int i = 0; i < 10; i++)
 {
     double price = rand.Next(1, 30) * rand.NextDouble();

     dgv.Rows[i].Cells[0].Value = "Product " + i;
     dgv.Rows[i].Cells[1].Value = "$ " + price;
 }

 //CLEARS THE DEFAULT SELECTION WHICH IS THE FIRST ROW
 dgv.ClearSelection();
4.) Build and Compile the project. The project can also be downloaded here.

OUTPUT:


Comments

Post a Comment

Popular posts from this blog

How to Create a Configuration.INI Files in VB6

How to Make Windows Form Transparent using Visual Basic 6/VB6

How to Set Windows Form Always on Top of Other Applications in VB6