How to use BindingSource and BindingNavigator in C#

By FoxLearn 11/21/2024 2:04:38 PM   7.68K
Using BindingSource and BindingNavigator in a Windows Forms application simplifies data binding and navigation in a user interface.

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

How to use BindingSource and BindingNavigator in C#?

You need to define the Users class which will be used to hold the Username and Password properties.

public class Users
{
    public string Username { get; set; }
    public string Password { get; set; }
}

Drag and drop DataGridView from Visual Toolbox onto your form designer, then design your form as shown below.

bindingsource in c#

Add a DataGridView, a BindingNavigator, and a BindingSource to the form.

c# bindingnavigator

Adding Users to a BindingSource and populating it with some sample data.

You'll need to bind the BindingSource to a DataGridView to display the Users data, then use the BindingNavigator to allow navigation through the BindingSource.

The DataGridView will automatically generate columns for Username and Password when you set the BindingSource as the DataSource.

Add code to handle your form as below

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 BindingSourceDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Add users to the BindingSource
            usersBindingSource.Add(new Users() { Username = "admin", Password = "admin" });
            usersBindingSource.Add(new Users() { Username = "user", Password = "123" });
            usersBindingSource.Add(new Users() { Username = "sa", Password = "admin" });
            usersBindingSource.Add(new Users() { Username = "lucy", Password = "123@qaz" });
        }
    }
}

The BindingNavigator will allow you to navigate through the users. You can use the "Next" and "Previous" buttons to move between users, and the "Add" and "Delete" buttons to modify the list of users.

You can also edit the Username and Password directly in the DataGridView, and those changes will be reflected in the BindingSource.

VIDEO TUTORIAL