Adding Multiple Columns and Rows in the DataGridView Programmatically Using C#.

This time, I’m going to teach you how to add multiple columns and rows in the Datagridview programmatically using C#. This method will illustrate on how to control the columns and rows by creating it manually inside the datagridview. This is a big help for you when you are a beginner in programming.

Creating an Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application in C#. ps1

Step 2

Do the form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, create a method for adding multiple columns and rows in the datagridview
  1.  
  2. private void add_Columns_Rows()
  3. {
  4. //setup the columns to be added.
  5. dataGridView1.ColumnCount = 5;
  6. //Set the columns name
  7. dataGridView1.Columns[0].Name = "ID";
  8. dataGridView1.Columns[1].Name = "Item";
  9. dataGridView1.Columns[2].Name = "Price";
  10. dataGridView1.Columns[3].Name = "Quantity";
  11. dataGridView1.Columns[4].Name = "Sub-Total";
  12.  
  13. //Set a value to be added in a row
  14. string[] row = new string[] { "1", "Cellphone", "15,000", "2", "30,000" };
  15. //adding rows in the datagridview
  16. dataGridView1.Rows.Add(row);
  17. //Set a value to be added in a row
  18. row = new string[] { "2", "Laptop", "21,000", "1", "21,000" };
  19. //adding rows in the datagridview
  20. dataGridView1.Rows.Add(row);
  21. //Set a value to be added in a row
  22. row = new string[] { "3", "Speaker", "2,000", "2", "4,000" };
  23. //adding rows in the datagridview
  24. dataGridView1.Rows.Add(row);
  25. //Set a value to be added in a row
  26. row = new string[] { "4", "Desktop Computer", "10,000", "5", "50,000" };
  27. //adding rows in the datagridview
  28. dataGridView1.Rows.Add(row);
  29. }

Step 4

Do the following codes to execute the method that you have created in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. //displaying the columns and rows.
  5. add_Columns_Rows();
  6. }
For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below

Add new comment