windowsforms-114682-controls-and-libraries-data-grid-getting-started-walkthroughs-data-binding-and-working-with-columns-tutorial-adonet-data.md
In this tutorial, you will learn how to do the following:
Watch Video: Bind Grid to SQL Database
Important
This tutorial targets .NET Framework. Since .NET 5+ design time does not support ADO.NET, you cannot use the .NET Form Designer to create a new ADO.NET data source. In .NET 5+, you can only reference existing DataSet objects. Both Microsoft and our team recommend that you use modern code-based ORMs (such as Entity Framework) to bind WinForms controls to database data. Refer to the following Microsoft blog post for details: Data Binding with the OOP Windows Forms Designer.
Invoke the grid control’s smart tag menu and open the Data Source Configuration Wizard.
Choose “ADO.NET Typed DataSet” and click New Data Source.
Select the Database source type and click Next.
Choose Dataset and click Next.
Choose an existing data connection or create and configure a new connection. This tutorial uses an existing connection to a local SQL Server Northwind database.
Specify the connection string name and click Next.
Select required tables and data fields in the database and click Finish.
In the grid control’s smart tag menu, open the drop-down menu next to the Choose Data Source option and select a table.
The following auto-generated code loads data into nwindDataSet:
void Form1_Load(object sender, EventArgs e) {
this.categoriesTableAdapter.Fill(this.nwindDataSet.Categories);
}
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
Me.categoriesTableAdapter.Fill(Me.nwindDataSet.Categories)
End Sub
The following code snippet handles the Form’s FormClosing event and calls the table adapter’s Update method to post changes to the database:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
categoriesTableAdapter.Adapter.Update(nwindDataSet);
}
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
categoriesTableAdapter.Adapter.Update(nwindDataSet)
End Sub
Tip
Read the following help topic for additional information: Post Data to an Underlying Data Source.
See Also
Data Binding Mechanism in ADO.NET
How to: Bind GridControl to Database and Implement Master-Detail Mode at Design Time