C# DataGridView - Set Selected Rows To TextBoxes

June 21, 2017 Oclemy C# TextBox, C# DataGridView 1 minute, 1 second

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.

Comments