How to Display the Current Row Into the TextBoxes Using C#

Passing data from the datagridview into the textbox is a common problem if you are a beginner in programming. So, in this tutorial, I will teach you how to display the current row into the textboxes using c#. This program is composed by adding column and rows in the datagridview programmatically and it will automatically display the data in the textbox when the datagridview cell is clicked. This is a big help for you to solve your current problem in programming and you can do it in no time. Follow the step by step guide to know how it works.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Do the form just like shown below. figure 1

Step 3

Double click the form and to the following codes for adding columns and rows automatically in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. //setup the columns to be added.
  5. dataGridView1.ColumnCount = 4;
  6. //Set the columns name
  7. dataGridView1.Columns[0].Name = "Item";
  8. dataGridView1.Columns[1].Name = "Price";
  9. dataGridView1.Columns[2].Name = "Quantity";
  10. dataGridView1.Columns[3].Name = "Sub-Total";
  11.  
  12. //Set a value to be added in a row
  13. string[] row = new string[] { "Cellphone", "15,000", "2", "30,000" };
  14. //adding rows in the datagridview
  15. dataGridView1.Rows.Add(row);
  16. //Set a value to be added in a row
  17. row = new string[] { "Laptop", "21,000", "1", "21,000" };
  18. //adding rows in the datagridview
  19. dataGridView1.Rows.Add(row);
  20. //Set a value to be added in a row
  21. row = new string[] { "Speaker", "2,000", "2", "4,000" };
  22. //adding rows in the datagridview
  23. dataGridView1.Rows.Add(row);
  24. //Set a value to be added in a row
  25. row = new string[] { "Desktop Computer", "10,000", "5", "50,000" };
  26. //adding rows in the datagridview
  27. dataGridView1.Rows.Add(row);
  28. }

Step 4

Write the following code for passing the data from the datagridview to the textboxes when the current row is selected.
  1.  
  2. private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
  3. {
  4. DataGridView dtg = new DataGridView();
  5. dtg = dataGridView1;
  6.  
  7. txtProduct.Text = dtg.CurrentRow.Cells[0].Value.ToString();
  8. txtPrice.Text = dtg.CurrentRow.Cells[1].Value.ToString();
  9. txtQauntity.Text = dtg.CurrentRow.Cells[2].Value.ToString();
  10. txtSubtotal.Text = dtg.CurrentRow.Cells[3].Value.ToString();
  11. }
The complete source code is included. You can download it and run it on your computer. 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