How to use BindingSource and BindingNavigator in C#
By FoxLearn 11/21/2024 2:04:38 PM 7.57K
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.
Add a DataGridView
, a BindingNavigator
, and a BindingSource
to the form.
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
- How to Print Text in a Windows Form Application Using C#
- How to fill ComboBox and DataGridView automatically in C#
- How to Read text file and Sort list in C#
- How to pass ListView row data into another Form in C#
- How to read and write to text file in C#
- How to make a Countdown Timer in C#
- How to Display selected Row from DataGridView to TextBox in C#
- How to Get all Forms and Open Form with Form Name in C#