C# DataGridView - Set Selected Rows To TextBoxes


DataGridView belongs to System.Windows.Forms namespace.

Needless to say, displaying data in tabular or grid-like format is a task we do commonly. And datagridview is a winform component that provides us with a complete solution to make applications that work with tabular data.

Today we explore at how to set the selected cell items to textboxes.

using System;
using System.Windows.Forms;

namespace DGView_To_TextBox
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      fillDGView();
    }

    private void fillDGView()
    {
        //SET COLUMNS
      dataGridView1.ColumnCount = 3;
      dataGridView1.Columns[0].Name = "Name";
      dataGridView1.Columns[1].Name = "Position";
      dataGridView1.Columns[2].Name = "Team";

      //ENABLE FULL ROW SELECTION
      dataGridView1.SelectionMode=DataGridViewSelectionMode.FullRowSelect;

        //ADD DATA
      String[] row = {"Gianluigi Buffon","GoalKeeper","AC Milan" };
      dataGridView1.Rows.Add(row);

      row = new String[] { "Iker Casilla", "Goalkeeper", "Real Madrid" };
      dataGridView1.Rows.Add(row);
      row = new String[] { "Landon Donovan", "Midfielder", "LA Galaxy" };
      dataGridView1.Rows.Add(row);
      row = new String[] { "Thomas Muller", "Striker", "Bayern Munich" };
      dataGridView1.Rows.Add(row);
      row = new String[] { "Mats Hummels", "Defender", "Borussia Dortmund" };
      dataGridView1.Rows.Add(row);

    }

    private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {

    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        nameTxt.Text = dataGridView1.SelectedRows[0].Cells["Name"].Value.ToString();
        positionTxt.Text = dataGridView1.SelectedRows[0].Cells["Position"].Value.ToString();
        teamTxt.Text = dataGridView1.SelectedRows[0].Cells["Team"].Value.ToString();
    }
  }
}

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post