DataGridView in C#

Introduction

In the previous tutorial, you have learned about the GridView in ASP.net web forms and to populate GridView automatically through UI data source option. In this tutorial, you will learn about DataGridView in C# Windows Form Application and you will be able to populate the DataGridView through C# code so that you can populate the DataGridView dynamically.

Create GridView in C# Windows Form

Drag and Drop

See GridView in ASP.net to see how to place GridView from Toolbox, In C# Windows Form Application, you can add DataGridView from Toolbox .

C# Code

You can create DataGridView in Windows Form using C# code.

Create Objects

  1. DataGridView
  2. Binding Source
  3.  Data Adapter

Add DataGridView in C# to Windows Form

In the constructor of the of the Windows Form, add the properties of the Form and DataGridView.

Populate DataGridView in C# through Database

Binding Data Source

After loading the form, and declaring and initializing the DataGridView bind the data source. You can bind your data source in the EventHandler you previously declared on Form Load.

Specify Connection String

Specify the connection string for your database.

Create SqlDataAdapter

Create a new dataAdapter and pass the connection string and the query to dataAdapter.

Create SqlCommandBuilder

Create a new commandBuilder for CRUD (Create Read Update Delete) operations on the database. Pass dataAdapter as arguments in SqlCommandBuilder.

Create DataTable and Bind to bindingSource

Create a new DataTable and bind it to the bindingSource.

Resize DataGridView to Fit new DataSource

Resize the old DataGridView to fit the newly added DataSource content by using DataGridViewAutoSizeColumnsMode.

Complete Code to Populate DataGridView

Output

DataGridView in C#
DataGridView in C#

Hope you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed!
Don’t forget to give your feedback through comments.