How to Display selected Row from DataGridView to TextBox in C#

By FoxLearn 11/28/2024 2:45:49 PM   4.61K
How to Display selected Row from DataGridView to TextBox in C#

In this article, we will explore how to use the DataGridView control in C# to display data from a database table, and how to capture the selected row to display its content in a TextBox.

Displaying Selected Row Data from DataGridView in a TextBox in C#

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "DataGridViewTextBox" and then click OK

We will start with a simple Windows Forms application that uses a DataGridView control to display data. The data will come from a database, which in this case is the Northwind database's Categories table.

Drag and drop the DataGridView and TextBox controls onto the form. The TextBox controls will display the data from the selected row of the DataGridView.

datagridview in c#

Create a new dataset, then select category table from Northwind database

c# dataset

Add a BindingSource to both the DataGridView and TextBox controls. After placing the DataGridView on the form, set its DataSource property to northwindDataSet.Categories to automatically display the data loaded in the Form1_Load method.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'northwindDataSet.Categories' table. You can move, or remove it, as needed.
            this.categoriesTableAdapter.Fill(this.northwindDataSet.Categories);

        }
    }
}

We use the categoriesTableAdapter.Fill method to load the Categories table from the northwindDataSet into the DataGridView. The categoriesTableAdapter queries the database and fills the dataset, which then automatically populates the DataGridView.

VIDEO TUTORIAL